C++ Map Library - upper_bound() Function


Advertisements


Description

The C++ function std::multimap::upper_bound() returns an iterator pointing to the first element which is greater than key k.

Declaration

Following is the declaration for std::multimap::upper_bound() function form std::map header.

C++98

iterator upper_bound (const key_type& k);
const_iterator upper_bound (const key_type& k) const;

Parameters

k − Key to be searched.

Return value

If object is constant qualified then method returns a constant iterator otherwise 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::upper_bound() function.

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

using namespace std;

int main(void) {
   /* Multimap with duplicates */
   multimap<char, int> m {
            {'a', 1},
            {'a', 2},
            {'b', 3},
            {'c', 4},
            {'d', 5}
         };

   auto it = m.upper_bound('a');

   cout << "Upper bound is" << endl;

   cout << it->first << " = " << it->second << endl;

   return 0;
}

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

Upper bound is
b = 3

map.htm

Advertisements