Home »
C++ STL
set::lower_bound() function in C++ STL
C++ STL set::lower_bound() function: Here, we are going to learn about the lower_bound() function of set in C++ STL (Standard Template Library).
Submitted by Radib Kar, on February 16, 2019
C++ STL set::lower_bound() function
set::lower_bound() function is a predefined function, it is used to get the lower bound of any element in a set.
it finds lower bound of any desired element from the set. Lower bound of any_element means the first number in the set that's not considered to go before any_element. So, if any_element is itself present, then it's any_element else immediate next of any_element.
Prototype:
set<T> st; //declaration
st<T> st::iterator it; //iterator declaration
it=st.upper_bound(T key);
Parameter: T key; //T is the data type
Return type: If lower_bound of the key exists in the set, Iterator pointer to the lower bound, Else, st.end()
Usage:
The function finds lower bound of any desired element from the set. Lower bound of x means the first number in the set that's not considered to go before x. So, if x is itself present, then it's x else immediate next of x.
Example:
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.lower_bound(6)
Print *it; //6
it=st.lower_bound(8)
Print *it; //10
Header file to be included:
#include <iostream>
#include <set>
OR
#include <bits/stdc++.h>
C++ implementation:
#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 lower_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<<"lower bound of 6 is "<<*(st.lower_bound(6));
return 0;
}
Output
Example of lower_bound function
inserting 4
inserting 6
inserting 10
Set contents are:
4 6 10
lower bound of 6 is 6