The std::map::find() function searches for an element with a specified key in a std::map. It is a member function of the std::map container and returns an iterator indicating the search result.
- Returns an iterator to the matching element if the key is found.
- Returns map::end() when the specified key does not exist in the map.
#include <iostream>
#include <map>
using namespace std;
int main(){
map<int, string> m = {
{1, "Apple"},
{2, "Banana"}
};
if (m.find(2) != m.end())
cout << "Key Found";
else
cout << "Key Not Found";
return 0;
}
Output
Key Found
Syntax
map_name.find(key);
Parameters: key - Key of the pair to be searched in the map container.
Return Value
- Returns an iterator pointing to the element if the key is found.
- Returns map::end() if the key does not exist in the map.
Working of map::find()
The find() function performs a key-based search in the map and returns an iterator indicating whether the requested element exists.
- Searches the map for the specified key and returns an iterator to the matching element.
- Returns map::end() when the requested key is not found in the container.
- Uses the balanced binary search tree structure of std::map to perform efficient lookups.
- Requires only O(log n) time complexity for searching, regardless of the element position.
Example: Using map::find()
#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!
Explanation
- find(2) returns an iterator pointing to the element {2, 30}.
- find(5) returns end() because the key does not exist.
- The returned iterator is compared with end() to determine whether the search was successful.
Applications
The find() function is commonly used when efficient key lookup is required.
- Checking whether a key exists before accessing or modifying it.
- Retrieving the value associated with a specific key.
- Avoiding duplicate key insertion.
- Implementing dictionary and lookup-based applications.
Advantages
Using map::find() provides several benefits.
- Performs efficient key lookup in logarithmic time.
- Returns an iterator that can be used directly for further operations.
- Avoids unnecessary traversal of the entire map.
- Works seamlessly with other STL map operations.