std::upper_bound and std::lower_bound for Vector in C++ STL
Click here for Set 1 and Set 2 of Vectors.
Vector – upper_bound and lower_bound
Iterator lower_bound (Iterator first, Iterator last, const val)
Iterator upper_bound (Iterator first, Iterator last, const val)
lower_bound returns an iterator pointing to the first element in the range [first,last) which has a value not less than ‘val’.
and if the value is not present in the vector then it returns the end iterator.
upper_bound returns an iterator pointing to the first element in the range [first,last) which has a value greater than ‘val’.
CPP
// lower_bound and upper_bound in vector #include <algorithm> // for lower_bound, upper_bound and sort #include <iostream> #include <vector> // for vector using namespace std; int main() { int gfg[] = { 5, 6, 7, 7, 6, 5, 5, 6 }; vector< int > v(gfg, gfg + 8); // 5 6 7 7 6 5 5 6 sort(v.begin(), v.end()); // 5 5 5 6 6 6 7 7 vector< int >::iterator lower, upper; lower = lower_bound(v.begin(), v.end(), 6); upper = upper_bound(v.begin(), v.end(), 6); cout << "lower_bound for 6 at position " << (lower - v.begin() + 1) << '\n' ; cout << "upper_bound for 6 at position " << (upper - v.begin() + 1) << '\n' ; return 0; } |
Output :
lower_bound for 6 at position 4 upper_bound for 6 at position 7
Time Complexity: O(n*log(n)) where n is the number of elements in the array.
Auxiliary Space: O(1)
Let us see the difference table with 5 useful differences that are as follows:
std::upper_bound | std::lower_bound |
It is used to return an iterator pointing to the last element in the range | It is used to return an iterator pointing to the first element in the range |
It is defined in <algorithm> header file. | It is defined in <algorithm> header file. |
Its return type is of integer. | Its return type is of integer. |
Its complexity is logarithmic. | Its complexity is logarithmic. |
If no element in the range compares greater than val, the function returns last. | If all the element in the range compare less than val, the function returns last |
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above
Please Login to comment...