Open In App

Searching in a map using std::map functions in C++

Last Updated : 14 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Usually, main purpose of using map stl container is for efficient search operations and sorted order retrieval. As map stores key-value pair, all the search operations take “O(log(n))” time (n is size of map). Different types of search functions exists in C++ language, each having different functions. In the context of competitive programming, this turns out to be useful when search operations are required and performs better than other containers. Some search operations are discussed below.

std::map::find()

find() is used to search for the key-value pair and accepts the “key” in its argument to find it. This function returns the pointer to the element if the element is found, else it returns the pointer pointing to the last position of map i.e “map.end()” .




// C++ code to demonstrate the working of find()
  
#include<iostream>
#include<map> // for map operations
using namespace std;
  
int main()
{
    // declaring map
    // of char and int
    map< char, int > mp;
      
    // declaring iterators
    map<char, int>::iterator it ;
    map<char, int>::iterator it1 ;
      
    // inserting values 
    mp['a']=5;
    mp['b']=10;
    mp['c']=15;
    mp['d']=20;
    mp['e']=30;
      
    // using find() to search for 'b' 
    // key found
    // "it" has address of key value pair.
    it = mp.find('b');
      
    if(it == mp.end())
        cout << "Key-value pair not present in map" ;
    else
        cout << "Key-value pair present : " 
          << it->first << "->" << it->second ;
      
    cout << endl ;
      
    // using find() to search for 'm' 
    // key not found
    // "it1" has address of end of map.
    it1 = mp.find('m');
      
    if(it1 == mp.end())
        cout << "Key-value pair not present in map" ;
    else
        cout << "Key-value pair present : " 
            << it1->first << "->" << it1->second ;
      
}


Output:

Key-value pair present : b->10
Key-value pair not present in map

std::map::lower_bound()

lower_bound() is also used for the search operation but sometimes also returns a valid key-value pair even if it is not present in map . lower_bound() returns address of key value pair, if one is present in map, else returns the address to the smallest key greater than key mentioned in its arguments. If all keys are smaller than the key to be found, it points to “map.end()” .




// C++ code to demonstrate the working of lower_bound()
  
#include<iostream>
#include<map> // for map operations
using namespace std;
  
int main()
{
    // declaring map
    // of char and int
    map< char, int > mp;
      
    // declaring iterators
    map<char, int>::iterator it ;
    map<char, int>::iterator it1 ;
    map<char, int>::iterator it2 ;
      
      
    // inserting values 
    mp['a']=5;
    mp['b']=10;
    mp['c']=15;
    mp['h']=20;
    mp['k']=30;
      
    // using lower_bound() to search for 'b' 
    // key found
    // "it" has address of key value pair.
    it = mp.lower_bound('b');
      
    if(it == mp.end())
        cout << "Key-value pair not present in map" ;
    else
        cout << "Key-value pair returned : " 
            << it->first << "->" << it->second ;
      
    cout << endl ;
      
    // using lower_bound() to search for 'd' 
    // key not found
    // "it1" has address of next greater key.
    // key - 'h'
    it1 = mp.lower_bound('d');
      
    if(it1 == mp.end())
        cout << "Key-value pair not present in map" ;
    else
        cout << "Key-value pair returned : " 
            << it1->first << "->" << it1->second ;
      
    cout << endl;
      
    // using lower_bound() to search for 'p' 
    // key not found
    // "it2" has address of next greater key.
    // all keys are smaller, hence returns mp.end()
    it2 = mp.lower_bound('p');
      
    if(it2 == mp.end())
        cout << "Key-value pair not present in map" ;
    else
        cout << "Key-value pair returned : "
            << it2->first << "->" << it2->second ;
      
}


Output:

Key-value pair returned : b->10
Key-value pair returned : h->20
Key-value pair not present in map

std::map::upper_bound()

upper_bound() is also used for the search operation and never returns the key-value pair searched for . upper_bound() returns address of key value pair coming exactly next to the searched key, if one is present in map. If all keys are smaller than the key to be found, it points to “map.end()”




// C++ code to demonstrate the working of upper_bound()
  
#include<iostream>
#include<map> // for map operations
using namespace std;
  
int main()
{
    // declaring map
    // of char and int
    map< char, int > mp;
      
    // declaring iterators
    map<char, int>::iterator it ;
    map<char, int>::iterator it1 ;
    map<char, int>::iterator it2 ;
      
      
    // inserting values 
    mp['a']=5;
    mp['b']=10;
    mp['c']=15;
    mp['h']=20;
    mp['k']=30;
      
    // using upper_bound() to search for 'b' 
    // key found
    // "it" has address of key value pair next to 'b' i.e 'c'.
    it = mp.upper_bound('b');
      
    if(it == mp.end())
        cout << "Key-value pair not present in map" ;
    else
        cout << "Key-value pair returned : " 
            << it->first << "->" << it->second ;
      
    cout << endl ;
      
    // using upper_bound() to search for 'd' 
    // key not found
    // "it1" has address of next greater key.
    // key - 'h'
    it1 = mp.upper_bound('d');
      
    if(it1 == mp.end())
        cout << "Key-value pair not present in map" ;
    else
        cout << "Key-value pair returned : " 
        << it1->first << "->" << it1->second ;
      
    cout << endl;
      
    // using upper_bound() to search for 'p' 
    // key not found
    // "it2" has address of next greater key.
    // all keys are smaller, hence returns mp.end()
    it2 = mp.upper_bound('p');
      
    if(it2 == mp.end())
        cout << "Key-value pair not present in map" ;
    else
        cout << "Key-value pair returned : " 
            << it2->first << "->" << it2->second ;
      
}


Output:

Key-value pair returned : c->15
Key-value pair returned : h->20
Key-value pair not present in map

std::map::equal-range

Yet another function to search in map, it returns the range containing the searched key. As map contains unique elements, range returned contains at most 1 element. This function returns a iterator of pair, whose 1st element points to lower_bound() of the searched key pair, and second element points to the upper_bound() of the searched key. If key is not present, both first element and second element point to the next greater element.




// C++ code to demonstrate the working of equal_range()
  
#include<iostream>
#include<map> // for map operations
using namespace std;
  
int main()
{
    // declaring map
    // of char and int
    map< char, int > mp;
      
    // declaring iterators
    pair<map<char, int>::iterator, map<char, int>::iterator> it;
      
      
    // inserting values 
    mp['a']=5;
    mp['b']=10;
    mp['c']=15;
    mp['h']=20;
    mp['k']=30;
      
    // using equal_range() to search for 'b' 
    // key found
    // 1st element of "it" has the address to lower_bound (b)
    // 2nd element of "it" has the address to upper_bound (c) 
    it = mp.equal_range('b');
      
    cout << "The lower_bound of key is : " 
        << it.first -> first << "->" << it.first -> second;
    cout << endl;
      
    cout << "The upper_bound of key is : " 
        << it.second -> first << "->" << it.second -> second;
      
    cout << endl << endl ;
      
    // using equal_range() to search for 'd' 
    // key not found
    // Both elements of it point to next greater key
    // key - 'h'
    it = mp.equal_range('d');
      
    cout << "The lower_bound of key is : " 
        << it.first -> first << "->" << it.first -> second;
    cout << endl;
      
    cout << "The upper_bound of key is : " 
        << it.second -> first << "->" << it.second -> second;
      
      
}


Output:

The lower_bound of key is : b->10
The upper_bound of key is : c->15

The lower_bound of key is : h->20
The upper_bound of key is : h->20



Similar Reads

std::fixed, std::scientific, std::hexfloat, std::defaultfloat in C++
Formatting in the standard C++ libraries is done through the use of manipulators, special variables or objects that are placed on the output stream. There are two types of floating point manipulators namely, fixed floating point and scientific floating point. These all are defined in header &lt;iostream&gt;. Use of precision : In the default floati
3 min read
std::oct , std::dec and std::hex in C++
This function is used to set the base to octal, decimal or hexadecimal. It sets the basefield format flag for the str stream to the specified base std::oct : When basefield is set to octal, integer values inserted into the stream are expressed in octal base (i.e., radix 8). For input streams, extracted values are also expected to be expressed in oc
2 min read
std::string::length, std::string::capacity, std::string::size in C++ STL
Prerequisite: String in C++ String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let's see a few of the functionalities string class provides. Header File &lt;string&gt; String Functionalities The
6 min read
std::stod, std::stof, std::stold in C++
std::stod() : It convert string into double. Syntax: double stod( const std::string&amp; str, std::size_t* pos = 0 ); double stod( const std::wstring&amp; str, std::size_t* pos = 0 ); Return Value: return a value of type double Parameters str : the string to convert pos : address of an integer to store the number of characters processed. This param
3 min read
std::setbase, std::setw , std::setfill in C++
The useful input/output manipulators are std::setbase, std::setw and std::setfill. These are defined in and are quite useful functions. std::base : Set basefield flag; Sets the base-field to one of its possible values: dec, hex or oct according to argument base.Syntax : std::setbase (int base);decimal : if base is 10hexadecimal : if base is 16octal
3 min read
std::stol() and std::stoll() functions in C++
std::stol(): This function converts the string, provided as an argument in the function call, to long int. It parses str interpreting its content as an integral number of the specified base, which is returned as a value of type long int. Syntax: long int stol (const string&amp; str, size_t* idx = 0, int base = 10) Parameters: The function accepts t
4 min read
std::tuple, std::pair | Returning multiple values from a function using Tuple and Pair in C++
There can be some instances where you need to return multiple values (maybe of different data types ) while solving a problem. One method to do the same is by using pointers, structures or global variables, already discussed here There is another interesting method to do the same without using the above methods,  using tuples (for returning multipl
2 min read
Difference between std::set vs std::vector in C++ STL
Vectors: Vectors are containers similar to dynamic arrays, with the ability to resize when a new element is inserted or deleted from it. It is a template of Standard Template Library or STL, which provides more flexibility to the program. Elements of vectors are placed in contiguous storage and are traversed using iterators. Examples: vector &lt;in
3 min read
std::istream_iterator and std::ostream_iterator in C++ STL
The STL is a very powerful library in C++. It is strongly built on the principles of template programming. The STL library has three main components : Containers: These classes define the data structures which are used to contain the data. The data may be stored in linked lists, or trees or arrays. The containers provided in the STL are vector, deq
6 min read
Difference between std::swap and std::vector::swap
The std::swap is a general function used to exchange the given values whereas the std::vector::swap is a specialized function that can swap all the contents of two different vector containers.Below are some major key differences between std::swap and std::vector::swap, std::swapstd::vector::swapThe std::swap() is a built-in function in C++ STL whic
3 min read
Practice Tags :
three90RightbarBannerImg