Переменные, захваченные в лямбда-выражении, по умолчанию равны const
, если вы не отметили лямбда как mutable
. unordered_map
не имеет operator[]
, который может быть вызван для объекта const unordered_map
, поскольку он вставляет (ie изменяет ) новый элемент, если запрошенный ключ не найден.
Кроме того, вы захватываете map
по значению , вместо этого вы должны захватить его по ссылке (если вы не ожидаете, что cmp
переживет map
).
Попробуйте это:
unordered_map<string, int> word_counts;
for (const auto& str : words) {
word_counts[str]++;
}
auto cmp = [&word_counts](const string &word1, const string &word2){
auto iter = word_counts.find(word1);
int count1 = (iter != word_counts.end()) ? iter->second : 0;
iter = word_counts.find(word2);
int count2 = (iter != word_counts.end()) ? iter->second : 0;
/* or, throw an exception if word1 or word2 are not found...
int count1 = word_counts.at(word1);
int count2 = word_counts.at(word2);
*/
if (count1 == count2)
return word1 < word2;
return count1 > count2; // <-- why > and not < ?
};