Printing an iterator index in std :: map

I use the find() method std::map , which returns an iterator.
However, I need the index of the item found; for example: 0, which corresponds to std::map::begin() , etc.

 #include <map> #include <utility> #include <iostream> int main() { std::map< int, int > aMap; aMap.insert( std::make_pair(100, 50) ); aMap.insert( std::make_pair(200, 40) ); aMap.insert( std::make_pair(300, 60) ); std::map< int, int >::iterator it_map = aMap.find(300); if (it_map != aMap.end()) std::cout << it_map << "\n"; // error } 

This does not compile, and I know the reason. However, I need a print method of 2 because the index 300 is 2.

For this simple example, you can say that a map (binary tree) is not a good container. However, in real code there are tons of elements that I need to look for, and a binary tree is suitable for this.

Any idea?

+5
source share
2 answers

If you need an index, perhaps the map is the wrong data type; you need to iterate over the map (in linear time) to find the index, losing the advantage of searching by logarithmic time.

Perhaps a sorted vector using the lower_bound algorithm to search for elements in logarithmic time might be more appropriate. You can then subtract the resulting random access iterator from the begin() iterator in constant time.

However, if you want to use the card:

 std::cout << std::distance(aMap.begin(), it_map) << '\n'; 
+7
source

Use std::distance , for example:

 std::cout << std::distance(std::begin(aMap),it_map) << endl; 

Documentation here

+5
source

Source: https://habr.com/ru/post/1202687/


All Articles