Tutorialspoint.dev

multimap equal_range() in C++ STL

The multimap::equal_range() is a built-in function in C++ STL which returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. If there are no matches with key K, the range returned is of length 0 with both iterators pointing to the first element that has a key considered to go after k according to the container’s internal comparison object (key_comp).

Syntax:

iterator multimap_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 an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. If there are no matches with key K, the range returned is of length 0 with both iterators pointing to the first element that has a key considered to go after k according to the container’s internal comparison object (key_comp).

Program below illustrate the above method:

// C++ program to illustrate the
// equal_range() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
  
    // initialize container
    multimap<int, int> mp;
    // insert elements in random order
    mp.insert({ 2, 30 });
    mp.insert({ 1, 40 });
    mp.insert({ 3, 60 });
    mp.insert({ 1, 20 });
    mp.insert({ 5, 50 });
  
    // Stores the range of key 1
    auto it = mp.equal_range(1);
  
    cout << "The multimap elements of key 1 is : ";
    cout << "KEY ELEMENT ";
  
    // Prints all the elements of key 1
    for (auto itr = it.first; itr != it.second; ++itr) {
        cout << itr->first
             << ' ' << itr->second << ' ';
    }
    return 0;
}

Output:

The multimap elements of key 1 is : 
KEY    ELEMENT
1    40
1    20


This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter