The std::map::find() is a built-in function in C++ STL that is used to find an element with given key in the map. It is a member function of std::map container so we can directly use it with any map.
Syntax
map_name.find(key)
Parameters
- key: Key of the pair to be searched in the map container.
Return Value
- If the key is found, it returns an iterator to the position where the key is present in the map.
- If the key is not found, it returns an iterator to the end of the map.
Example of map::find()
// C++ program for illustration of map::find()
// function
#include <bits/stdc++.h>
using namespace std;
int main() {
// Creating a map
map<int, int> mp;
mp.insert({2, 30});
mp.insert({1, 40});
mp.insert({3, 20});
mp.insert({4, 50});
// key1 find (exist in the map)
int key1 = 2;
// key2 find (does not exist in the map)
int key2 = 5;
auto it = mp.find(key1);
// Check if key1 is found
if (it != mp.end()) {
cout << "Key '" << it->first << "' found with";
cout << " value: " << it->second << endl;
}
// Element not present
else
cout << "Key '" << key1 << "' not found!" << endl;
it = mp.find(key2);
// Check if key2 is found
if (it != mp.end()) {
cout << "Key '" << it->first << "' found with";
cout << " value: " << it->second;
}
// key2 not found
else
cout << "Key '" << key2 << "' not found!";
return 0;
}
Output
Key '2' found with value: 30 Key '5' not found!
Complexity Analysis of map::find()
std::map container in C++ is implemented using some Balanced Binary Search Tree (mostly R-B Tree). So,
- Time Complexity: O(log n), where n is the number of elements.
- Auxiliary Space: O(1)