Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) std::binary_search

 

std::binary_search is an STL algorithm to determine if a value is present in a sorted container.

 

 

 

 

 

Project and source code

 

Operating system: Ubuntu 10.04 LTS Lucid Lynx

IDE: Qt Creator 2.0.0

Project type: Qt4 console Application

Compiler: G++ 4.4.1

Libraries used:

 

 

 

 

 

 

main.cpp

 

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

struct Gossip
{
  Gossip(const int any_i) : i(any_i) {}
  private:
  int i;
  friend bool operator<(const Gossip& lhs, const Gossip& rhs);
};

bool operator<(const Gossip& lhs, const Gossip& rhs)
{
  std::cout << "bool operator<(const Gossip& lhs, const Gossip& rhs)\n";
  return lhs.i < rhs.i;
}

int main()
{
  std::vector<Gossip> v;
  for (int i=0; i!=100; ++i)
  {
    v.push_back(Gossip(i));
  }

  std::cout << "I will be found\n";
  assert(std::binary_search(v.begin(),v.end(),Gossip(90))==true);
  std::cout << "I will not be found\n";
  assert(std::binary_search(v.begin(),v.end(),Gossip(100))==false);
}

 

Screen output:

 

I will be found bool operator<(const Gossip& lhs, const Gossip& rhs) bool operator<(const Gossip& lhs, const Gossip& rhs) bool operator<(const Gossip& lhs, const Gossip& rhs) bool operator<(const Gossip& lhs, const Gossip& rhs) bool operator<(const Gossip& lhs, const Gossip& rhs) bool operator<(const Gossip& lhs, const Gossip& rhs) bool operator<(const Gossip& lhs, const Gossip& rhs) bool operator<(const Gossip& lhs, const Gossip& rhs) I will not be found bool operator<(const Gossip& lhs, const Gossip& rhs) bool operator<(const Gossip& lhs, const Gossip& rhs) bool operator<(const Gossip& lhs, const Gossip& rhs) bool operator<(const Gossip& lhs, const Gossip& rhs) bool operator<(const Gossip& lhs, const Gossip& rhs) bool operator<(const Gossip& lhs, const Gossip& rhs)

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict