C++ Unordered_multimap Library - equal_range() Function


The C++ function std::unordered_multimap::equal_range() returns range of elements that matches specific key.

The range is defined by two iterators, one points to the first element that is not less than key k and another points to the first element greater than key k.


Following is the declaration for std::unordered_multimap::equal_range() function form std::unordered_map() header.


pair<iterator,iterator> equal_range(const key_type& k);
pair<const_iterator,const_iterator> equal_range(const key_type& k) const;


k − Key to be searched.

Return value

If object is constant qualified then method returns a pair of constant iterator otherwise pair of non-constant iterator.

Time complexity

Constant i.e. O(1) in average case.

Linear i.e. O(n) in worst case.


The following example shows the usage of std::unordered_multimap::equal_range() function.

#include <iostream>
#include <unordered_map>

using namespace std;

int main(void) {
   unordered_multimap<char, int> umm = {
            {'a', 1},
            {'b', 2},
            {'b', 3},
            {'b', 4},
            {'c', 5}

   auto ret = umm.equal_range('b');

      cout << "Elements associated with key 'b': ";

      for (auto it = ret.first; it != ret.second; ++it)
         cout << it->second << " ";
      cout << endl;

   return 0;

Let us compile and run the above program, this will produce the following result −

Elements associated with key 'b': 4 3 2