What is the purpose of the lower_bound function in C++?
In C++, the lower_bound function is used to search for the insertion position of a particular value in sorted containers (such as vector, array, deque, set, etc.), or find the position of the first element greater than or equal to a given value.
Specifically, the lower_bound function will return an iterator pointing to the first element in the container that is not less than the given value. If there is an element in the container that is equal to the given value, the lower_bound function will also return an iterator pointing to that element. If there is no element in the container that is not less than the given value, the lower_bound function will return an iterator pointing to the end of the container.
The format for using the lower_bound function is as follows:
iterator lower_bound (iterator first, iterator last, const T& val);
In this case, first and last are iterators that represent the range of the container, while val is the value to search for. The lower_bound function searches within the range of [first, last) and returns the iterator of the first element that is not less than val.
Here is an example:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {1, 3, 5, 7, 9};
int val = 4;
std::vector<int>::iterator it = std::lower_bound(nums.begin(), nums.end(), val);
if (it != nums.end()) {
std::cout << "The first element not less than " << val << " is " << *it << std::endl;
} else {
std::cout << "No element not less than " << val << " in the vector" << std::endl;
}
return 0;
}
The output is:
The first element not less than 4 is 5
In the above example, the lower_bound function searches for elements that are not less than 4, and returns an iterator pointing to 5.