I am now sorting a string in decreasing order based on the frequency of characters. For example: the input is "apple", I must output "ppale". Because character 'p' appears twice and the others only appear once. so 'p' must be placed to the left most.
Here is my code:
string frequencySort(string s) {
if(s.size() == 0) return "";
unordered_map<char,int> map;
for(auto c : s)
map[c]++; //record the frequency of each characters
sort(s.begin(),s.end(),
[=](char a, char b){return map[a] > map[b] || map[a]==map[b]&&a<b;}
);
return s;
}
But compiler shows error:
passing ‘const std::unordered_map<char, int>’ as ‘this’ argument discards qualifiers
on [=](char a, char b){return map[a] > map[b] || map[a]==map[b]&&a<b;}
.
However, if I capture local variable by reference, i.e.
[&](char a, char b){return map[a] > map[b] || map[a]==map[b]&&a<b;}
it works.
Could anyone please tell my why I cannot capture by value?