In C++, the std::lower_bound() is a built-in function used to find the position of an element in a sorted range that has a value not less than the given value. It is defined inside the <algorithm> header file. In this article, we will learn about std::lower_bound() function in C++.
Example:
C++
// C++ program to illustrate the use of std::lower_bound
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {10, 20, 30, 40, 50};
// Finding lower bound for value 35 in vector v
cout << *lower_bound(v.begin(), v.end(), 35);
return 0;
}
Syntax of lower_bound()
std::lower_bound (first, last, val, comp);
Parameters
- first: Iterator to the first element in the range.
- last: Iterator to the theoretical element just after the last element in the range.
- val: Value to be compared.
- comp(optional): Binary function that accepts and compares val with an element in the range. By default, it returns true if the element in the range is smaller than val, false otherwise.
Return Value
- Returns an iterator to the smallest number greater than or equal to val.
- If all the elements in the range are less than the given value, returns iterator to the end of the range.
- If all the elements in the range are greater than given value, returns iterator to the beginning of the range.
Note: If the range is not sorted or at least partitioned with respect to the given value, the behaviour of this function is undefined.
The std::lower_bound function is useful for finding the first position where a value can be inserted in a sorted range.
More Examples of std::lower_bound()
The std::lower_bound() function is an interesting function that can be used for number of applications. The below examples demonstrate some of its common uses.
Find the Lower Bound of a Value in Array
C++
// C++ program to find the lower bound of a value in a
// vector using std::lower_bound()
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int n = sizeof(arr)/sizeof(arr[0]);
// Finding lower bound for value 35 in array arr
cout << *lower_bound(arr, arr + n, 35);
return 0;
}
Time Complexity: O(log n), where n is the number of elements in the array.
Auxiliary Space: O(1)
Find lower_bound() in a Vector of String Using Custom Comparator
C++
// C++ program to illustrate how to use custom
// comparator with std::lower_bound() function
#include <bits/stdc++.h>
using namespace std;
// Custom comparator for case-insensitive comparison
bool comp(const string &a,const string &b) {
return lexicographical_compare(a.begin(), a.end(),
b.begin(), b.end(), [](char c1,char c2) {
return tolower(c1) < tolower(c2);
});
}
int main()
{
vector<string> v = {"Apple", "banana", "Cherry",
"date", "Elderberry"};
// Finding lower bound of "Avocado"
auto lb = lower_bound(v.begin(), v.end(), "Avocado", comp);
// Checking if lower bound is found
if (lb != v.end())
cout << *lb;
else
cout << "Lower bound not found!";
return 0;
}
Time Complexity: O(log n), where n is the number of elements in the vector.
Auxiliary Space: O(1)
Explanation: We need to use the custom comparator function to perform the case insensitive search as the default comparator treats the uppercase and lowercase differently.
Find the Existence of an Element in Vector
C++
// C++ Program to check if the element exists
// in a vector using lower_bound()
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {10, 20, 30, 40, 50};
int val = 40;
// Cheking if val exists in the vector v
auto it = lower_bound(v.begin(), v.end(), val);
if (*it == val)
cout << val << " is found.";
else
cout << val << " is NOT found.";
return 0;
}
Time Complexity: O(log n), where n is the number of elements in vector.
Auxiliary Space: O(1)
Explanation: The lower_bound() function will return the iterator to the given value if it is present in the vector. If it is not present, it will return iterator to the largest element smaller than the given value.
Find the Number of Smaller and Larger Elements than a Value in Vector
C++
// C++ Program to count the elements smaller and larger
// than a value in a vector using lower_bound()
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {10, 20, 30, 40, 50};
int val = 35;
// Finding lower and upper bound of val in v
auto lb = lower_bound(v.begin(), v.end(), val);
// Finding the number of smaller elements
cout << "No. of Smaller Elements: " << lb - v.begin()
<< endl;
// Finding the number of larger elements
cout << "No. of Larger Elements: " << v.size() -
(lb - v.begin());
return 0;
}
OutputNo. of Smaller Elements: 3
No. of Larger Elements: 2
Time Complexity: O(log n), where n is the number of elements in vector.
Auxiliary Space: O(1)
Explanation: The lower_bound() function will return the iterator to the first element just greater than or equal to the given value in the vector. As the vector is sorted, all the elements previous to this iterator will be less than the give value, so we can subtract the vector.begin() iterator from the iterator returned by the lower_bound() to get the number of smaller elements. We can then find the number of greater elements by subtracting this number from the total number of elements.
Insert an Element in a Sorted Vector
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {10, 20, 30, 40, 50};
int val = 35;
// Finding lower and upper bound of val in v
auto lb = lower_bound(v.begin(), v.end(), val);
// Inserting 35 to its correct position
v.insert(lb, val);
for (auto i: v)
cout << i << " ";
return 0;
}
Explanation: The lower_bound() returns the position by which the vector is partitioned with respect to the given value. In other words, if the element was present in the sorted vector, it would be present at this position.
Finding the Lower Bound in a Set
C++
// C++ program to find the lower bound of a value in a
// vsetector using std::lower_bound()
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s = {10, 20, 30, 40, 50};
// Finding lower bound for value 35 in array arr
cout << *lower_bound(s.begin(), s.end(), 35);
return 0;
}
Time Complexity: O(n)
Space Complexity: O(1)
Explanation: The time complexity is O(n) for the set is because it doesn’t provide random access to its elements. So, the lower_bound() function have to increment it sequentially to find the middle element (part of binary search algorithm) each time leading to increased time complexity. However, std::set have their own specialized version named as set::lower_bound() method.
Similar Reads
C++ Programming Language
C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides: Hands-on application of different programming concepts.Similar syntax to
5 min read
Object Oriented Programming in C++
Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
6 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
11 min read
Vector in C++ STL
In C++, vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted. SyntaxVector is defined as the std::vector class template inside the <vector> header file. [GFGTABS] C+
9 min read
Templates in C++
C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types. For example, same sorting algorithm can work for different type, so
10 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot
8 min read
30 OOPs Interview Questions and Answers [2025 Updated]
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15+ min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. We will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class?A class is a user-defined data type, which holds its own data membe
9 min read
C++ Polymorphism
The word polymorphism means having many forms. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So, the same person exhibits different behaviour in different situations. This is ca
5 min read
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object a
6 min read