unordered_map equal_range in C++
Last Updated :
27 Nov, 2018
Improve
The unordered_map::equal_range() is an inbuilt function in C++ STL which is used to return the bounds of a range that includes all the elements in the container with a key that compares equal to k. The unordered_map containers are the container where keys are unique, the range will include one element at most. The range is defined by two iterators,
CPP
CPP
- The first one pointing to the first element of the range.
- The second one pointing past the last element of the range.
// C++ program to implement
// unordered_map::equal_range() function
#include <iostream>
#include <unordered_map>
using namespace std;
// main program
int main()
{
unordered_map <int, int> map = { { 1, 3 },
{ 1, 2 },
{ 3, 1 },
{ 2, 3 } };
for (int j = 1; j <= 3; j++) {
auto range = map.equal_range(j);
//'auto' is a keyword
for (auto i = range.first; i != range.second; i++) {
// iterates first to last
cout << "first : " << i->first;
cout << "\nsecond : " << i->second << endl
<< endl;
}
}
}
Output:
Program 2:
first : 1 second : 3 first : 2 second : 3 first : 3 second : 1
// C++ program to search 'unordered map' container
#include <iostream>
#include <unordered_map>
using namespace std;
// Rename 'unordered_map<int, char>' as 'gfg'
typedef unordered_map<char, char> gfg;
int main()
{
// 'g' is object
gfg g;
// Container values
// Contents are look like [a, b] [c, d] [e, f]
g.insert(gfg::value_type('a', 'b'));
g.insert(gfg::value_type('b', 'd'));
g.insert(gfg::value_type('e', 'f'));
// Look into the syntax part above
// here 'f' is key
pair<gfg::iterator, gfg::iterator> p1 = g.equal_range('f');
// 'f' is not exits, so no output for 'f'
cout << "search for 'f' :";
for (; p1.first != p1.second; ++p1.first) {
cout << p1.first->first << ", " << p1.first->second << endl;
}
// Successful search
// Here 'a' is key
p1 = g.equal_range('a');
// 'a' is exits, so it searched successfully
cout << "\nsearch for 'a' : [";
for (; p1.first != p1.second; ++p1.first) {
cout << p1.first->first << ", " << p1.first->second << "]";
}
return 0;
}
Output:
Complexity:
search for 'f' : search for 'a' : [a, b]
- Average case: Linear in the number of elements with the key k, which is constant.
- worst case: Linear in the size of the container.