In C++, std::map::find()searches for a key and returns an iterator to the pair that has it. Through the iterator you can read it->first (the key) and it->second (the value).
If the key is not in the map, find() returns end(). Always compare with end() before you use the result. Unlike m[key], find()never adds a key, and unlike at() it never throws. Include <map> to use it.
This is a member of std::map<Key, T>, a sorted container of key and value pairs. Each key is unique and the pairs are always kept in key order, so a map can find, insert, and erase a key in logarithmic time. Read a value with at() or find(). The m[key] operator also works, but it adds a default value when the key is missing.
Syntax
Pass the key and compare the result with end().
C++
auto it = m.find("Raj");
if (it != m.end()) {
std::cout << it->first << " " << it->second;
}
Call
What it does
m.find(key)
Returns an iterator to the pair with key, or m.end() if it is not found.
cm.find(key)
On a const map it returns a const_iterator, which can read but not change the value.
Never write *m.find(k) without checking. When the key is missing, find() returns end(), and dereferencing end() is undefined behavior.
The function takes the map by const reference. That is why it uses find(): operator[] does not work on a const map.
For "apple", find() succeeds and the function returns the stored 5. For "kiwi" it returns end(), so the function gives back the fallback -1.
The size is still 2, which proves that looking up a missing key with find() adds nothing.
Frequently Asked Questions
An iterator to the pair that has the key, or end() if the key is not in the map.
Compare the result with m.end(). If it is not equal to end(), the key was found.
find() never adds a key. m[key] adds the key with a default value when it is missing, which changes the map and its size.
at() returns the value and throws std::out_of_range when the key is missing. find() returns an iterator and gives end() for a missing key, with no exception.
It takes logarithmic time because a map is a balanced tree. For a million keys, that is about 20 comparisons.