The iterator acts like a pointer to the vector, so use the arrow, i.e., indirection, notation:
vecIter->find("alpha");
質問
I want to access specific elements in a vector of maps. My code is as follows:
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main() {
std::vector<map <string, int> > vecOfMaps;
map <string, int> myMap;
for (int j = 0; j < 10; j++) {
myMap["alpha"] = j;
myMap["beta"] = j*2;
vecOfMaps.push_back(myMap);
}
int start = 3;
int end = 5;
int counter = start;
for (std::vector<map <string, int> >::iterator vecIter = vecOfMaps.begin()+start; vecIter != vecOfMaps.begin()+end; ++vecIter) {
map<string, int>::iterator mapIter = vecIter.find("alpha");
cout << "\n vecElement " << counter << " mapString " << mapIter->first << " mapInt " << mapIter->second;
counter++;
}
return 0;
}
However, this code gives the following compilation error:
error: ‘std::vector, int> >::iterator’ has no member named ‘find’
map::iterator mapIter = vecIter.find("alpha");
How to find an entry inside a map in a vector of maps?
解決
The iterator acts like a pointer to the vector, so use the arrow, i.e., indirection, notation:
vecIter->find("alpha");