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
Aucun commentaire:
Enregistrer un commentaire