The map::find() is a built-in function in C++ STL that returns an iterator or a constant iterator that refers to the position where the key is present in the map. If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map.end()
.
Syntax:
iterator=map_name.find(key)
or
constant iterator=map_name.find(key)
Parameters: The function accepts one mandatory parameter key, which specifies the key to be searched in the map container.
Return Value: The function returns an iterator or a constant iterator which refers to the position where the key is present in the map. If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map.end().
Time Complexity for Searching Element:
The time complexity for searching elements in std::map is O(log n). Even in the worst case, it will be O(log n) because elements are stored internally as a Balanced Binary Search tree (BST) whereas, in std::unordered_map best case and average case time complexity for searching is O(1) because elements are stored in a Hash table and therefore the key acts as an index while searching in unordered maps. But the worst-case time complexity for searching is O(N).
Below is the illustration of the above function:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
map< int , int > m;
m.insert({ 2, 30 });
m.insert({ 1, 40 });
m.insert({ 3, 20 });
m.insert({ 4, 50 });
int s1=2;
int s2=5;
cout << "Element " <<s1;
if (m.find(s1)!=m.end()){
cout<< " : found : Value : " <<m[s1]<<endl;
}
else cout<< " : Not found" <<endl;
cout << "Element " <<s2;
if (m.find(s2)!=m.end()){
cout<< " : found : Value : " <<m[s2];
}
else cout<< " : Not found" <<endl;
return 0;
}
|
Output
Element 2 : found : Value : 30
Element 5 : Not found
Time Complexity: O(log n)
Auxiliary Space: O(n)
Below code is a program to print all the elements after finding a element:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
map< int , int > mp;
mp.insert({ 2, 30 });
mp.insert({ 1, 40 });
mp.insert({ 3, 20 });
mp.insert({ 4, 50 });
cout << "Elements from position of 3 in the map are : \n" ;
cout << "KEY\tELEMENT\n" ;
for ( auto itr = mp.find(3); itr != mp.end(); itr++) {
cout << itr->first << '\t' << itr->second << '\n' ;
}
return 0;
}
|
Output
Elements from position of 3 in the map are :
KEY ELEMENT
3 20
4 50
Time Complexity: O(log n)
Auxiliary Space: O(n)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
21 Sep, 2023
Like Article
Save Article