I have a std::map called myMap in my C++ application, and I want to get an element using either myMap.find(key) or myMap[key]. However, I would also like to get the index of that element in the map.
std::map<string, int> myMap; // Populate myMap with a bunch of items... myElement = myMap["myKey"]; // Now I need to get the index of myElement in myMap   Is there a clean way to do that?
Thank you.
int k = distance(mymap. begin(), mymap. find(mykey)); It will give you the index of the key element.
Your map is not supposed to be accessed that way, it's indexed by keys not by positions. A map iterator is bidirectional, just like a list , so the function you are using is no more inefficient than accessing a list by position. If you want random access by position then use a vector or a deque .
Search for a place on Google MapsAt the top, tap the search box and enter an address, name of a place, or choose a category, like gas stations or groceries. Tip: After you find a place on the map, you can check directions to the place in a list, details about a place, or get directions with voice-guided navigation.
Using std::find_if algorithm For instance, find the index of the first 2-digit number in the array. The recommended approach is to use the std::find_if algorithm, which accepts a predicate to handle such cases. That's all about finding the index of an element in an array in C++.
I came here seeking for this answer but i found this distance function takes 2 iterators and returns an index
cout << distance(mymap.begin(),mymap.find("198765432"));   hope this helps :D
A std::map doesn't really have an index, instead it has an iterator for a key / value pair.  This is similar to an index in that it represents a position of sorts in the collection but it is not numeric.  To get the iterator of a key / value pair use the find method 
std::map<string, int>::iterator it = myMap.find("myKey"); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With