Lower bound and upper bound of C++
3 min readFeb 4, 2020
Lower bound and upper bound in STL
- upper_bound() and lower_bound() are standard library functions in C++.
- upper_bound() returns an iterator pointing to the first element in the range [first, last) that is greater than the value. If no such an element is found, return end().
- lower_bound() returns an iterator pointing to the first element in the range [first, last) which is greater or equal to the value. If no such an element is found, return end().
Quick summary
- upper bound return first element which is > value. If not, return end().
- lower bound return first element which is ≥ value. If not, return end().
Examples
#include <bits/stdc++.h>
int main()
{
std::vector<int> v{ 10, 20, 30, 30, 50 };
// Print vector
std::cout << "Vector contains :";
for (unsigned int i = 0; i < v.size(); i++)
std::cout << " " << v[i];
std::cout << "\n";
std::vector<int>::iterator low, upp;
std::cout<<"******* lower_bound *********"<<std::endl;
low = std::lower_bound(v.begin(), v.end(), 20);
std::cout << "\nlower_bound for element 20 at position : " << (low - v.begin());
low = std::lower_bound(v.begin(), v.end(), 25);
std::cout << "\nlower_bound for element 25 at position : " << (low - v.begin())<<std::endl;
std::cout<<"****** upper_bound ************"<<std::endl;
upp =…