Use binary_search() to binary search a vector : binary_search « STL Algorithms Binary search « C++ Tutorial






#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
typedef vector <string> VECTOR_STRINGS;
int main ()
{
    VECTOR_STRINGS v;

    v.push_back ("A");
    v.push_back ("B");
    v.push_back ("C");
    v.push_back ("D");

    // insert a duplicate into the vector
    v.push_back ("D");

    for (size_t nItem = 0; nItem < v.size (); ++ nItem){
        cout << "Name [" << nItem << "] = \"";
        cout << v [nItem] << "\"" << endl;
    }

    // sort the names using std::sort
    sort (v.begin (), v.end ());
    for (size_t nItem = 0; nItem < v.size (); ++ nItem){
        cout << "Name [" << nItem << "] = \"";
        cout << v [nItem] << "\"" << endl;
    }

    bool bElementFound = binary_search (v.begin (), v.end (),"C");

    if (bElementFound)
        cout << "Result: C was found in the vector!" << endl;
    else
        cout << "Element not found " << endl;

    return 0;
}








26.1.binary_search
26.1.1.Illustrating the generic binary search algorithms
26.1.2.Use binary_search to locate a value in a vector
26.1.3.binary_search a list
26.1.4.Use binary_search() to binary search a vector
26.1.5.Binary search after sorting