The map::equal_range() is a built-in function in C++ STL which returns a pair of iterators. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. Since the map container only contains unique key, hence the first iterator in the pair returned thus points to the element and the second iterator in the pair points to the next key which comes after key K. If there are no matches with key K and the key K is greater than largest key , the range returned is of length 1 with both iterators pointing to the an element which has a key denoting the size of map and elements as 0. Otherwise the lower bound and the upper bound points to the element just greater than the key K.
Syntax:
iterator map_name.equal_range(key)
Parameters: This function accepts a single mandatory parameter key which specifies the element whose range in the container is to be returned.
Return Value: The function returns a pair of iterators as explained above.
Below programs illustrate the above method:
Program 1:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
map< int , int > mp;
mp.insert({ 4, 30 });
mp.insert({ 1, 40 });
mp.insert({ 6, 60 });
pair<map< int , int >::iterator,
map< int , int >::iterator>
it;
it = mp.equal_range(1);
cout << "The lower bound is "
<< it.first->first
<< ":" << it.first->second;
cout << "\nThe upper bound is "
<< it.second->first
<< ":" << it.second->second;
return 0;
}
|
Output:
The lower bound is 1:40
The upper bound is 4:30
Program 2:
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
map< int , int > mp;
mp.insert({ 4, 30 });
mp.insert({ 1, 40 });
mp.insert({ 6, 60 });
pair<map< int , int >::iterator,
map< int , int >::iterator>
it;
it = mp.equal_range(10);
cout << "The lower bound is "
<< it.first->first << ":"
<< it.first->second;
cout << "\nThe upper bound is "
<< it.second->first
<< ":" << it.second->second;
return 0;
}
|
Output:
The lower bound is 3:0
The upper bound is 3:0
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 :
05 Mar, 2021
Like Article
Save Article