If I have a structure like
std::map<string, int> myMap;
myMap["banana"] = 1;
myMap["apple"] = 1;
myMap["orange"] = 1;
How can I access myMap[0]?
I know that the map sorts internally and I’m fine with this, I want to get a value in the map by index. I’ve tried myMap[0] but I get the error:
Error 1 error C2679: binary '[' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
I realise I could do something like this:
string getKeyAtIndex (map<string, int>& myMap, int index){
map<string, int>::const_iterator end = myMap.end();
int counter = -1;
for (map<string, int>::const_iterator it = myMap.begin(); it != end; ++it) {
counter++;
if (counter == index)
return it->first;
}
}
But surely this is hugely inefficient? Is there a better way?
Your
mapis not supposed to be accessed that way, it’s indexed by keys not by positions. Amapiterator is bidirectional, just like alist, so the function you are using is no more inefficient than accessing alistby position. If you want random access by position then use avectoror adeque.Your function could be written with help from
std::advance(iter, index)starting frombegin():