Next Spaceship

Driving into future...

STL Function: Binary_search()

| Comments

In some cases, we just want to if an element exists in a sorted list, then we can use the STL function: binary_search(). To use this function, you must include the header <algorithm>. Note before we use binary_search(), the list must be sorted, either in ascending order or in descending order. …… Here is a simpler example explaining how to use this function.

#include <algorithm>
#include <iostream>
#include <utility>
using namespace std;
#define N 20
int a[N];
int main() {
    sort(a, a + N);
    if (binary_search(a, a + N, 1)) {
        cout << "OK";
    }
}

Comments