In C++, std::unordered_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 unordered_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 <unordered_map> to use it.
This is a member of std::unordered_map<Key, T>, a hash table of key and value pairs. Each key is unique. Find, insert, and erase are usually average constant time. Unlike std::map, keys are not sorted and iteration order is unspecified. 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 unordered_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 unordered_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 unordered_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 average constant time because an unordered_map is a hash table. For a million keys, that is usually a few hash lookups.