multimap find() in C++

In this tutorial, we will learn how to use multimap find() in C++. Before directly moving to multimap find() in C++, lets first understand what is multimap in C++.

Multimap is similar to a map where both were associative containers. It stores elements in key-value pairs. The map generally stores unique keys. Whereas the multimap can store duplicate keys. And internally it keeps elements in sorted order by keys.

Now let us understand multimap find in detail.

multimap find()

The multimap::find() is an built-in C++ standard library function.Where the find() function returns iterator or the constant iterator. The iterator, which the function returns is nothing but the position(of the key) in the multimap container. Now there is a time when is key could not be found. Then, it returns either an iterator or a constant iterator that mention to the multimap.end().

Syntax of the multimap find() in C++

iterator multimap_anyname.find(any_key_name);
            (or)
const iterator multimap_anyname.find(any_key_name);

The key is the position to be searched in the multimap container.

The multimap find() function returns :

The multimap::find() function returns iterator or the constant iterator. The iterator, which the function returns is nothing but the position(of the key) in the multimap container. Now there is a time when is key could not be found. Then, it returns either an iterator or a constant iterator that mention to the multimap.end().

//illustraing use of multimap find() in c++
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
  
    // initialize multimap container 
    multimap<char, int> mm; 
  
    // insert elements in any random order 
    mm.insert({'b', 22 }); 
    mm.insert({'a', 10 }); 
    mm.insert({'b', 25 }); 
    mm.insert({'c', 20 }); 
    mm.insert({'e', 60 }); 
    mm.insert({'d', 50 });  

    cout << "The key value pairs after the key c are : \n"; 
    cout << "KEY\tVALUE\n"; 
  
    // find() function finds the position at key c 
    for (auto i = mm.find('c'); i != mm.end(); i++) 
        cout << i->first 
             << '\t' << i->second << '\n'; 
  
    return 0; 
}

Hence, the above code displays the following output :

The key value pairs after the key c are :
KEY	ELEMENT
c	20
d	50
e	60

Therefore, the code finds the position of the key named c. And from there onwards it displays all the key-value pairs i.e., for the keys c,d,e it displays the values 20,50,60.

Recommended tutorials: 

Frequency of each character in a string using map in C++

Sequence Containers in C++

Leave a Reply

Your email address will not be published. Required fields are marked *