CPP STL Tutorial : C++ Binary search operation that can be performed on containers

Binary search can be performed on sorted data.
lower_bound : It will return an iterator pointing to the first element in the range [first,last) which does not compare less than val.
upper_bound : It will return an iterator pointing to the first element in the range [first,last) which compares greater than val.
equal_range : It will return the bounds of the subrange that includes all the elements of the range [first,last) with values equivalent to val.
binary_search : Test if value exists in sorted sequence
To use these operations, below header should be included:
#include <algorithm>
#include <iostream>
#include <vector>
#include <array>
#include <algorithm>    // std::all_of

//for more tutorials on C, C++, STL, DS visit www.ProDeveloperTutorial.com
using namespace std;

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

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

  std::cout << "looking for a 30... ";
  if (std::binary_search (v.begin(), v.end(), 30))
    std::cout << "found!\n"; 
    else std::cout << "not found.\n";
    
  std::vector<int>::iterator low,up;
  low=std::lower_bound (v.begin(), v.end(), 20);
  up= std::upper_bound (v.begin(), v.end(), 20);

  std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
  std::cout << "upper_bound at position " << (up - v.begin()) << '\n';
    
  return 0;
}

Output:

looking for a 30... found!
lower_bound at position 3
upper_bound at position 6
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *