Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an element in a specified range in std::map?

Is there an equivalent version of std::find(first, last) but for a std::map? I.e., is there a version of std::map's find method that searches for an element in a map, but restricting the search only to a specified [first, last) range? Ideally, the solution should be logarithmic in the size of [first, last).

From what I've seen, std::map::find itself doesn't support this functionality (it always searches the whole map).

like image 300
Anakhand Avatar asked Feb 21 '19 14:02

Anakhand


People also ask

How do I find the element in std::map?

map find() function in C++ STL If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map. end(). Time Complexity for Searching element : The time complexity for searching elements in std::map is O(log n).

How do you check if an element exists in a map C++?

To check for the existence of a particular key in the map, the standard solution is to use the public member function find() of the ordered or the unordered map container, which returns an iterator to the key-value pair if the specified key is found, or iterator to the end of the container if the specified key is not ...

Is Unordered_map faster than map?

Note: unordered_map container performs faster than map when they have to access an individual element by their key.


1 Answers

You can use std::lower_bound, std::upper_bound or std::equal_range for that as std::map iterators and data in the map satisfy the requirement for those functions, though you should be aware that it will be less efficient than std::map::find() due to linear iterator increments.

From std::lower_bound documentation

The number of comparisons performed is logarithmic in the distance between first and last (At most log 2(last - first) + O(1) comparisons). However, for non-LegacyRandomAccessIterators, the number of iterator increments is linear.

emphasis is mine.

like image 65
Slava Avatar answered Oct 17 '22 01:10

Slava