C++ multimap::upper_bound() Function



The C++ std::multimap::upper_bound() function is used to return an iterator pointing to the first element greater than the specified key. It is useful for finding the position where a new element could be inserted without disturbing the sorted order. unlike map, multimap allows duplicate keys, so upper_bound() provides access to the first element greater than the key, rather than the exact match. The time complexity of this function is logarithmic i.e. O(log n).

Syntax

Following is the syntax for std::multimap::upper_bound() function.

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

Parameters

  • k − It indicates the key to search for.

Return value

This function returns an iterator to the first element in the container.

Example

Let's look at the following example, where we are going to demonstrate the usage of the upper_bond() function.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {
        {1, "AB"}, {2, "BC"}, {3, "CD"}, {4, "DE"}
    };
    auto x = a.upper_bound(2);
    if (x != a.end()) {
        std::cout << "First element greater than key is : ";
        std::cout << x->first << " --> " << x->second << std::endl;
    } else {
        std::cout << "No elements is greater than key." << std::endl;
    }
    return 0;
}

Output

Following is the output of the above code −

First element greater than key is : 3 --> CD

Example

Consider another scenario, where we are going to use the upper_bound() function in the loop.

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {
        {1, "TP"}, {2, "Hi"}, {3, "Hello"}, {3, "Vanakam"}
    };
    for (auto x = a.upper_bound(1); x != a.end(); ++x) {
        std::cout << x->first << " --> " << x->second << std::endl;
    }
    return 0;
}

Output

Output of the above code is as follows −

2 --> Hi
3 --> Hello
3 --> Vanakam

Example

In the following example, we are going to use the upper_bound() function in combination with equal_range().

#include <iostream>
#include <map>
int main()
{
    std::multimap<int, std::string> a = {
        {1, "TP"}, {1, "TutorialsPoint"}, {2, "Tutorix"}, {3, "Welcome"}
    };
    auto x = a.equal_range(1);
    auto y = a.upper_bound(1);
    std::cout << "Elements with given key : " << std::endl;
    for (auto z = x.first; z != x.second; ++z) {
        std::cout << z->first << " --> " << z->second << std::endl;
    }
    if (y != a.end()) {
        std::cout << "First element greater than key is :  ";
        std::cout << y->first << " --> " << y->second << std::endl;
    } else {
        std::cout << "No elements is greater than key." << std::endl;
    }
    return 0;
}

Output

If we run the above code it will generate the following output −

Elements with given key : 
1 --> TP
1 --> TutorialsPoint
First element greater than key is :  2 --> Tutorix
multimap.htm
Advertisements