Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of element in C++ map

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.

like image 445
SZH Avatar asked Jul 25 '13 15:07

SZH


People also ask

How do you find the index of an element on a map?

int k = distance(mymap. begin(), mymap. find(mykey)); It will give you the index of the key element.

Can you access map by index?

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 .

How do you search on a map?

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.

How do you find the index of an array element in C++?

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++.


2 Answers

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

like image 183
Mahmoud Aladdin Avatar answered Sep 28 '22 05:09

Mahmoud Aladdin


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"); 
like image 33
JaredPar Avatar answered Sep 28 '22 04:09

JaredPar