Set upper_bound() function in C++ STL

C++Server Side ProgrammingProgramming

In this article we are going to discuss the set::upper_bound() in C++ STL, their syntax, working and their return values.

What is Set in C++ STL?

Sets in C++ STL are the containers which must have unique elements in a general order. Sets must have unique elements because the value of the element identifies the element. Once added a value in set container later can’t be modified, although we can still remove or add the values to the set. Sets are used as binary search trees.

What is set::upper_bound()?

upper_bound() is an inbuilt function in C++ STL which is declared in <set> header file. upper_bound() returns an iterator to the upper bound of the value whose upper bound we wish to find. The function returns iterator pointing to the immediate next element of the value whose upper bound we wish to find.

Syntax

name_of_set.upper_bound(const type_t& value);

Parameter

This function accepts a parameter, i.e. The value whose upper bound is to be found.

Return value

This function returns an iterator pointing to the immediate next element which is greater than the value

Example

Input: set<int> myset = {1, 2, 3, 4, 5};
   Myset.upper_bound(3);
Output: Upper bound = 4

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   set<int> Set;
   Set.insert(9);
   Set.insert(7);
   Set.insert(5);
   Set.insert(3);
   Set.insert(1);
   cout<<"Elements are : ";
   for (auto i = Set.begin(); i!= Set.end(); i++)
      cout << *i << " ";
   auto i = Set.upper_bound(5);
   cout <<"\nupper bound of 5 in the set is: ";
   cout << (*i) << endl;
   i = Set.upper_bound(1);
   cout<<"upper bound of 1 in the set is: ";
   cout << (*i) << endl;
   return 0;
}

Output

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

upper bound of 5 in the set is: 7
upper bound of 1 in the set is: 3

Example

 Live Demo

#include <iostream>
#include <set>
int main (){
   std::set<int> Set;
   std::set<int>::iterator one, end;
   for (int i=1; i<10; i++)
   Set.insert(i*10);
   one = Set.lower_bound (20);
   end = Set.upper_bound (40);
   Set.erase(one , end); // 10 20 70 80 90
   std::cout<<"Elements are: ";
   for (std::set<int>::iterator i = Set.begin(); i!=Set.end(); ++i)
      std::cout << ' ' << *i;
   std::cout << '\n';
   return 0;
}

Output

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

Elements are : 10 50 60 70 80 90
raja
Published on 05-Mar-2020 10:36:21
Advertisements