mardi 5 mai 2020

error in accessing surrounding variable in lambda function

...
        unordered_map<string ,int> map;
        for (const auto& str : words) {
            map[str]++;
        }
        auto cmp = [map](string s1, string s2){
            if (map[s1] == map[s2])
                return s1 < s2;
            return map[s1] > map[s2];
        };
...

This give me no viable overloaded operator[] for type 'const unordered_map<std::__cxx11::string, int>' (aka 'const unordered_map<basic_string<char>, int>')

But if I don't use [] operator but rather use .at() for access. The code compiles.

I don't know why. I check out [] operator and .at() : both have the same method signature.

Aucun commentaire:

Enregistrer un commentaire