multimap upper_bound() function in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax, and examples of multimap::upper_bound() function in C++ STL.

What is Multimap in C++ STL?

Multimaps are the associative containers, which are similar to map containers. It also facilitates to store the elements formed by a combination of key-value and mapped value in a specific order. In a multimap container there can be multiple elements associated with the same key. The data is internally always sorted with the help of its associated keys.

What is multimap::upper_bound()?

multimap::upper_bound() function is an inbuilt function in C++ STL, which is defined in <map> header file. upper_bound() returns an iterator to the upper bound of the multimap container. This function returns an iterator which points to the last element which is considered to go after the key k.

Syntax

Map_name.upper_bound(key& k);

Parameter

This function accepts only 1 parameter −

  • k − The key which we want to search.

Return value

This function returns the iterator which is pointing to the next element of the key ‘k’ which is to be considered to go after the key k.

Input 

map<char, int> newmap;
newmap(make_pair(‘a’, 1));
newmap(make_pair(‘b’, 2));
newmap(make_pair(‘c’, 3));
newmap.upper_bound(b);

Output 

c:3

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   //creating a multimap
   multimap<int, int> mul;
   mul.insert({ 2, 10 });
   mul.insert({ 1, 20 });
   mul.insert({ 1, 30 });
   mul.insert({ 3, 40 });
   mul.insert({ 3, 50 });
   mul.insert({ 4, 60 });
   // upper bound of 1
   auto i = mul.upper_bound(1);
   cout << "Upper bound of key 1 is: ";
   cout << (*i).first << " "<<(*i).second << endl;
   // upper bound of 2
   i = mul.upper_bound(2);
   cout << "Upper bound of key 2 is: ";
   cout << (*i).first << " " <<(*i).second << endl;
   // upper bound of 3
   i = mul.upper_bound(3);
   cout << "Upper bound of key 3 is: ";
   cout << (*i).first << " " << (*i).second << endl;
   return 0;
}

Output

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

Upper bound of key 1 is: 2 10
Upper bound of key 2 is: 3 40
Upper bound of key 3 is: 4 60
raja
Published on 22-Apr-2020 11:59:31
Advertisements