function template
<algorithm>
std::binary_search default (1)template <class ForwardIterator, class T> bool binary_search (ForwardIterator first, ForwardIterator last, const T& val);custom (2)
template <class ForwardIterator, class T, class Compare> bool binary_search (ForwardIterator first, ForwardIterator last, const T& val, Compare comp);
Test if value exists in sorted sequence
Returnstrue
if any element in the range [first,last)
is equivalent to val, and false
otherwise.
The elements are compared using operator<
for the first version, and comp for the second. Two elements, a and b are considered equivalent if (!(a<b) && !(b<a))
or if (!comp(a,b) && !comp(b,a))
.
The elements in the range shall already be sorted according to this same criterion (operator<
or comp), or at least partitioned with respect to val.
The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted range, which is specially efficient for random-access iterators.
The behavior of this function template is equivalent to:
1
2
3
4
5
6
template <class ForwardIterator, class T>
bool binary_search (ForwardIterator first, ForwardIterator last, const T& val)
{
first = std::lower_bound(first,last,val);
return (first!=last && !(val<*first));
}
[first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
[first,last)
as either operand of operator<
.
bool
. The value returned indicates whether the first argument is considered to go before the second.
true
if an element equivalent to val is found, and false
otherwise.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// binary_search example
#include <iostream> // std::cout
#include <algorithm> // std::binary_search, std::sort
#include <vector> // std::vector
bool myfunction (int i,int j) { return (i<j); }
int main () {
int myints[] = {1,2,3,4,5,4,3,2,1};
std::vector<int> v(myints,myints+9); // 1 2 3 4 5 4 3 2 1
// using default comparison:
std::sort (v.begin(), v.end());
std::cout << "looking for a 3... ";
if (std::binary_search (v.begin(), v.end(), 3))
std::cout << "found!\n"; else std::cout << "not found.\n";
// using myfunction as comp:
std::sort (v.begin(), v.end(), myfunction);
std::cout << "looking for a 6... ";
if (std::binary_search (v.begin(), v.end(), 6, myfunction))
std::cout << "found!\n"; else std::cout << "not found.\n";
return 0;
}
looking for a 3... found! looking for a 6... not found.
log2(N)+2
element comparisons (where N is this distance).
[first,last)
are accessed.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4