C++ Unordered_multimap Library - equal_range() Function



Description

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.

Declaration

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

C++11

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

Parameters

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.

Example

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
unordered_map.htm
Advertisements