TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C++ algorithm lower_bound() function

C++ algorithm lower_bound() function with c++ tutorial for beginners and professionals with examples on adjacent_find(),any_of(), copy(), copy_if(), count(), count_if(), equal(), find(), find_end(), find_first_of(), find_if(), find_if_not(), for_each() etc.

<< Back to CPP

C++ Algorithm lower_bound()

C++ Algorithm lower_bound() function is the version of binary search. This function is used to return an iterator pointing to the first element in an ordered range [first, last) that is not less than (i.e. greater than or equal to) to the specified value val.

The first version uses operator < to compare the elements and the second version uses comp function.

Syntax

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

Parameter

first: A forward iterator pointing to the first element in the range to be searched.

last: A forward iterator pointing to the past last element in the range to be searched.

comp: A user-defined binary predicate function that accepts two arguments and returns true if the two arguments are in order and false otherwise. It follows the strict weak ordering to order the elements.

val: A value of the lower bound to compare the elements in the range.

Return value

It returns an iterator pointing to the first element of the range that is not less than val or last if no such element is found.

Complexity

On average, complexity is logarithmic in the distance between first and last: performs up to log2 (N) + 1 element comparisons Where N = last - first.

Data races

The object in the range [first, last) are accessed.

Exceptions

This function throws an exception if either an element comparison or an operation on iterator throws an exception.

Note: The invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of lower_bound():

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

using namespace std;

int main()
{

  vector<int> v = {3, 1, 4, 6, 5};


  decltype(v)::iterator it = lower_bound(v.begin(), v.end(), 4);

  cout << *it << ", pos = " << (it - v.begin()) << endl;
  return 0;
  
}

Output:

4, pos = 2

Example 2

Let's see another simple example:

#include <iostream>     // std::cout
#include <algorithm>    // std::lower_bound, std::upper_bound, std::sort
#include <vector>       // std::vector

using namespace std;

int main () {
  int myints[] = {10,20,30,30,20,10,10,20};
  vector<int> v(myints,myints+8);           // 10 20 30 30 20 10 10 20

  sort (v.begin(), v.end());                // 10 10 10 20 20 20 30 30

  vector<int>::iterator low,up;
  low=lower_bound (v.begin(), v.end(), 20); //          ^
  up= upper_bound (v.begin(), v.end(), 20); //                   ^

  cout << "lower_bound at position " << (low- v.begin()) << '\n';
  cout << "upper_bound at position " << (up - v.begin()) << '\n';

  return 0;
}

Output:

lower_bound at position 3
upper_bound at position 6

Example 3

Let's see another simple example:

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

using namespace std;
 
template<class ForwardIt, class T, class Compare=less<>>
ForwardIt binary_find(ForwardIt first, ForwardIt last, const T& value, Compare comp={})
{
    // Note: BOTH type T and the type after ForwardIt is dereferenced 
    // must be implicitly convertible to BOTH Type1 and Type2, used in Compare. 
    // This is stricter than lower_bound requirement (see above)
 
    first = lower_bound(first, last, value, comp);
    return first != last && !comp(value, *first) ? first: last;
}

int main() 
{
    vector<int> data = { 1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6 };
 
    auto lower = lower_bound(data.begin(), data.end(), 4);
    auto upper = upper_bound(data.begin(), data.end(), 4);
 
    copy(lower, upper, ostream_iterator<int>(cout, " "));
 
    cout << '\n';
 
    // classic binary search, returning a value only if it is present
 
    data = { 1, 2, 4, 6, 9, 10 }; 
 
    auto it = binary_find(data.cbegin(), data.cend(), 4); //< choosing '5' will return end()
 
    if(it != data.cend())
      cout << *it << " found at index "<< distance(data.cbegin(), it);
 
    return 0;
}

Output:

4 4 4 
4 found at index 2

Example 4

Let's see another simple example:

#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;
}

Output:

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

Next TopicC++ Algorithm




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf