简体   繁体   中英

`[ ]` operator leads to compile error on map

I am trying to get an element from a map in a for loop. Following the example on cppreference I try this:

#include <iostream>
#include <map>

using namespace std;

int main()
{
    map<int, int> mapping;

    mapping.insert(pair<int, int>(11,1));
    mapping.insert(pair<int, int>(12,2));
    mapping.insert(pair<int, int>(13,3));

    for (const auto &it : mapping)
        mapping[it]++;


    cout << "array: ";
    for (const auto &it : mapping)
        cout << it.second << " ";

    return 0;
}

Which gives the following compilation error with gcc:

main.cpp: In function 'int main()':
main.cpp:15:16: error: no match for 'operator[]' (operand types are 'std::map<int, int>' and 'const std::pair<const int, int>')
         mapping[it]++;

If I understand it correctly the problem is that the auto is resolved to a std::pair<const int, int> for which no [] operator is defined. I was wondering whether there is a way to get this to work.

See for the full compilation error here

How about just

for (auto &it : mapping)
    ++it.second;

for your first loop?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM