unordered_map equal_range() Function in C++ with Examples

C++ unordered_map equal_range() Function: Here, we will learn about the equal_range() function, its usages, syntax and examples.
Submitted by Shivang Yadav, on July 20, 2022

unordered_map:

An unordered_map is a special type of container that stores data in the form of key-value pairs in an unordered manner. The key stored is used to identify the data value mapped to it uniquely.

std::unordered_map::equal_range() Function

The equal_range() function is used to return a new pair that contains the upper and lower values of range in unordered_map that contains the key value which is equal to K (value passed as parameters to function). The range has two values, the first one pointing to the first element and the second one pointing to the last element of the range.

std::unordered_map::equal_range() Function Syntax:

unordered_map.equal_range(K);

Parameter(s): It accepts a single value which is the value to be compared with the key value in unordered_map.

Return Value: It returns a pair which is the range containing the value matching K.

C++ unordered_map equal_range() Function Example:

#include <iostream>
#include <unordered_map>
using namespace std;

int main()
{
    unordered_map<int, char> map = { { 1, 'b' }, { 2, 's' }, { 3, 'q' }, { 8, 'z' }, { 5, 'a' } };

    cout << "For value key -> 5 : \t";
    auto range = map.equal_range(5);
    for (auto i = range.first; i != range.second; i++) {
        cout << "first : " << i->first << "\t";
        cout << "second : " << i->second;
    }

    cout << "\nFor value key -> 9 : \t";
    range = map.equal_range(9);
    for (auto i = range.first; i != range.second; i++) {
        cout << "first : " << i->first << "\t";
        cout << "second : " << i->second;
    }

    cout << "\nFor value key -> 2 : \t";
    range = map.equal_range(2);
    for (auto i = range.first; i != range.second; i++) {
        cout << "first : " << i->first << "\t";
        cout << "second : " << i->second;
    }
    
    return 0;
}

Output:

For value key -> 5 :    first : 5       second : a
For value key -> 9 : 
For value key -> 2 :    first : 2       second : s



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.