C++ Map Library - equal_range() Function


Advertisements


Description

The C++ function std::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::multimap::equal_range() function form std::map header.

C++98

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

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.

Exceptions

No effect on container if exception is thrown.

Time complexity

Logarithmic i.e. O(log n)

Example

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

Live Demo
#include <iostream>
#include <map>

using namespace std;

int main(void) {
   multimap<char, int> m = {
      {'a', 1},
      {'b', 2},
      {'b', 3},
      {'b', 4},
      {'d', 5}
        };

   auto ret = m.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': 2 3 4 

map.htm

Advertisements