How to use the unordered_map::equal_range() function in C++

Overview

In this shot, we will learn to use the unordered_map::equal_range() function.

The unordered_map::equal_range() function is available in the <unordered_map> header file in C++. It is used to obtain all the elements based on the specified key in the unordered map. In an unordered map, the key will always be unique, and hence we will always get one pair containing the key and the value.

Syntax

The syntax of the unordered_map::equal_range() function is given below:

pair<iterator1, iterator2> equal_range(K Key);

Parameter

The unordered_map::equal_range() function accepts the parameter mentioned below:

  • Key: The key-value that needs to be searched for.

Return value

The unordered_map::equal_range() function returns a pair of iterators:

  • iterator1: It specifies the lower bound of the range.
  • iterator2: It specifies the upper bound of the range.

In unordered maps, there will always be one unique key, and hence the first and second iterators will point to the value corresponding to the specified key.

Code

Let’s have a look at the code below:

#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<int,int> umap ={
{12, 32},
{166, 59},
{89, 90},
{66, 46}
};
auto range = umap.equal_range(166);
for (auto i = range.first; i != range.second; i++)
{
cout << "Key : " << i -> first << endl;
cout << "Value : " << i -> second << endl;
}
return 0;
}

Explanation

  • Lines 1 and 2: We import the required header files.

  • Line 5: We define a main() function.

  • Lines 7 to 12: We initialize an unordered map with integer type keys and values.

  • Line 14: We use unordered_map::equal_range() function to obtain the lower and upper bound iterators for a given key = 166$.

  • Lines 16 to 20: We use a loop to access both the returned iterators and print the key-value pairs using the lower and upper bound in a given limit for the key.

By following the code above, we can use the unordered_map::equal_range() function in C++.

Free Resources