Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

map find() function in C++ STL

  • Difficulty Level : Easy
  • Last Updated : 28 Oct, 2020

The map::find() is a built-in function in C++ STL which 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. 

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

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 Balanced Binary Search tree (BST) whereas, in std::unordered_map best case time complexity for searching is O(1).

Below is the illustration of the above function: 

CPP




// C++ program for illustration
// of map::find() function
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    // Initialize container
    map<int, int> mp;
 
    // Insert elements in random order
    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";
 
    // find() function finds the position
    // at which 3 is present
    for (auto itr = mp.find(3); itr != mp.end(); itr++) {
       
        cout << itr->first << '\t' << itr->second << '\n';
    }
 
    return 0;
}
Output
The elements from position 3 in map are : 
KEY    ELEMENT
3    20
4    50

My Personal Notes arrow_drop_up
Recommended Articles
Page :