Open In App

lower_bound in C++

The lower_bound() method in C++ is used to return an iterator pointing to the first element in the range [first, last) which has a value not less than val. This means that the function returns an iterator pointing to the next smallest number just greater than or equal to that number. If there are multiple values that are equal to val, lower_bound() returns the iterator of the first such value.
The elements in the range shall already be sorted or at least partitioned with respect to val. 
Templates: 

Syntax 1: 
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val); 
Syntax 2: 
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val, Compare comp); 
 



Parameters: The above methods accept the following parameters.  

Return Value: An iterator to the lower bound of val in the range. If all the elements in the range compare less than val, the function returns last. If all the elements in the range are larger than val, the function returns a pointer to the first element. 
Examples: 



Input: 10 20 30 40 50
Output: lower_bound for element 30 at index 2

Input: 10 20 30 40 50
Output: lower_bound for element 35 at index 3

Input: 10 20 30 40 50
Output: lower_bound for element 55 at index 5 (Basically, 55 is not present, so it returns end() iterator)

Input: 10 20 30 30 30 40 50
Output: lower_bound for element 30 at index 2




// CPP program to illustrate
// std :: lower_bound
#include <bits/stdc++.h>
  
// Driver code
int main()
{
    // Input vector
    std::vector<int> v{ 10, 20, 30, 30, 30, 40, 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 low1, low2, low3;
      
    // std :: lower_bound
    low1 = std::lower_bound(v.begin(), v.end(), 30);
    low2 = std::lower_bound(v.begin(), v.end(), 35);
    low3 = std::lower_bound(v.begin(), v.end(), 55);
  
    // Printing the lower bounds
    std::cout
        << "\nlower_bound for element 30 at position : "
        << (low1 - v.begin());
    std::cout
        << "\nlower_bound for element 35 at position : "
        << (low2 - v.begin());
    std::cout
        << "\nlower_bound for element 55 at position : "
        << (low3 - v.begin());
  
    return 0;
}

Output
Vector contains : 10 20 30 30 30 40 50

lower_bound for element 30 at position : 2
lower_bound for element 35 at position : 5
lower_bound for element 55 at position : 7

Time Complexity:  The number of comparisons performed is logarithmic. Therefore, the time complexity of the above approach is O(logN), where N = size. (last – first)


Article Tags :
C++