(C++) std::binary\_search
February 24, 2017 · View on GitHub
(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
Libraries used:
- STL: from GCC, shipped with Qt Creator 2.0.0
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)