×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

set::upper_bound() function in C++ STL

C++ STL set::upper_bound() function: Here, we are going to learn about the upper_bound() function of set in C++ STL (Standard Template Library).
Submitted by Radib Kar, on February 16, 2019

C++ STL set::upper_bound() function

set::upper_bound() function is a predefined function, it is used to get the upper bound of any element in a set.

It finds upper bound of any desired element from the set. Upper bound of any_element means the first number in the set that's immediate next to any_element.

The function finds upper bound of any desired element from the set. Upper bound of x is immediate next of x.

Syntax

set<T> st; //declaration
set<T> st::iterator it; //iterator declaration

it=st.upper_bound(T key);

Parameter(s)

It accepts a "key" of T type.

Return value

If upper_bound of the key exists in the set iterator pointer to the upper bound, Else, st.end()

Sample Input and Output

For a set of integer,
set<int> st;
st.insert(6);
st.insert(4);
st.insert(10);
set content: //sorted always(ordered)
 4
 6
10

it=st.upper_bound(4)
Print *it; //6

Header file

Header file to be included:

#include <iostream>
#include <set>
OR
#include <bits/stdc++.h>

Example

#include <bits/stdc++.h>
using namespace std;

void printSet(set<int> st) {
  set<int>::iterator it;
  cout << "Set contents are:\n";
  if (st.empty()) {
    cout << "empty set\n";
    return;
  }
  for (it = st.begin(); it != st.end(); it++) cout << *it << " ";
  cout << endl;
}

int main() {
  cout << "Example of upper_bound function\n";
  set<int> st;
  set<int>::iterator it;
  cout << "inserting 4\n";
  st.emplace(4);
  cout << "inserting 6\n";
  st.emplace(6);
  cout << "inserting 10\n";
  st.emplace(10);

  printSet(st);  // printing current set

  cout << "upper bound of 6 is " << *(st.upper_bound(6));

  return 0;
}

Output

Example of upper_bound function
inserting 4
inserting 6
inserting 10
Set contents are:
4 6 10
upper bound of 6 is 10 

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.