C++ Algorithm Library - lower_bound() Function


Advertisements

Description

The C++ function std::algorithm::lower_bound() finds the first element not less than the given value. This function excepts element in sorted order. It uses binary function for comparison.

Declaration

Following is the declaration for std::algorithm::lower_bound() function form std::algorithm header.

C++98

template <class ForwardIterator, class T, class Compare>
ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last,
   const T& val, Compare comp);

Parameters

  • first − Forward iterator to the initial position.

  • last − Forward iterator to the final position.

  • val − Value of the lower bound to search for in the range.

  • comp − A binary function which accepts two arguments and returns bool.

Return value

Returns an iterator to the first element not less than the given value. If all the element in the range compare less than val, then function returns last.

Exceptions

Throws exception if either the binary function or an operation on an iterator throws exception.

Please note that invalid parameters cause undefined behavior.

Time complexity

Linear.

Example

The following example shows the usage of std::algorithm::lower_bound() function.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool ignore_case(char a, char b) {
   return(tolower(a) == tolower(b));
}

int main(void) {
   vector<char> v = {'A', 'b', 'C', 'd', 'E'};
   auto it = lower_bound(v.begin(), v.end(), 'C');

   cout << "First element which is greater than \'C\' is " << *it << endl;

   it = lower_bound(v.begin(), v.end(), 'C', ignore_case);

   cout << "First element which is greater than \'C\' is " << *it << endl;

   it = lower_bound(v.begin(), v.end(), 'z', ignore_case);

   cout << "All elements are less than \'z\'." << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

First element which is greater than 'C' is b
First element which is greater than 'C' is d
All elements are less than 'z'.
algorithm.htm
Advertisements