C++ map find() Function
Example
Find the element with the key "Bo":
map<string, int> people = {{"John", 32}, {"Adele", 45}, {"Bo", 29}};
auto it = people.find("Bo");
if (it != people.end()) {
cout << it->first << " is: " << it->second;
} else {
cout << "Not found";
}
Definition and Usage
The find() function searches for an element with the given key, and returns an iterator (a pointer-like object that points to an element) to it.
If the key does not exist, find() returns end(). Always compare the result with end() before you use it.
The find function is defined in the <map> header file.
Syntax
map.find(keyType key)
keyType is the type of the keys in the map, like string in the example.
Parameter Values
| Parameter | Description |
|---|---|
| key | Required. The key to search for. |
Technical Details
| Returns: | An iterator pointing to the element with the given key. If the key does not exist, it returns map.end(). |
|---|
Related Pages
Read more about maps in our Maps Tutorial.