Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::map have a find member function?

Tags:

c++

stl

stdmap

A colleague and I were discussing the relative merits of member vs. non-member functions. A question arose: why does std::map have a find member function.

My answer was that although you can use std::find on maps, you must search for the key-value pair, or use find_if and e.g. a lambda. However, this is linear and map.find offers a search by key in better than linear time. I ended with the assertion that if it could have been a non-member, then it would have been! (Although, std::string suggests that I might have been somewhat hasty in my generalization).

My colleague pointed out that it would be possible to implement find the same way as a non-member function using map.lower_bound.

Is there a rationale for map.find having been made a member?

like image 353
Kaz Dragon Avatar asked Jul 25 '18 08:07

Kaz Dragon


People also ask

What does find function do in map in C++?

C++ map find() function is used to find an element with the given key value k. If it finds the element then it returns an iterator pointing to the element. Otherwise, it returns an iterator pointing to the end of the map, i.e., map::end().

Can we use Find function in map?

find() is used to search for the key-value pair and accepts the “key” in its argument to find it. This function returns the pointer to the element if the element is found, else it returns the pointer pointing to the last position of map i.e “map.

How do you check if a key exists in a map in 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 ...


1 Answers

A big objection to implementing std::find searching for a key on std::map as a non-member function is that doing so would prevent you from implementing the current version of std::find, which searches for a key-value pair.

Being an associative container, std::map contains key-value pairs. Non-member std::find is defined for all containers as a function that searches for an item in the container, which must be a key-value pair for std::map; using std::find to look up an item by its key would be inconsistent.

Obviously, one could implement std::find_by_key function applicable only to maps, but such function would always have a specialization based on the type of map. This provides no improvement in the API design over adding a member-function.

like image 125
Sergey Kalinichenko Avatar answered Sep 29 '22 19:09

Sergey Kalinichenko