398 CHAPTER 17. THE STANDARD TEMPLATE LIBRARY, GENERIC ALGORITHMS
17.4.4 binary_search()
• Header file:
#include ..
• Function prototypes:
– bool binary_search(ForwardIterator first, ForwardIterator last,
Type const &value);
– bool binary_search(ForwardIterator first, ForwardIterator last,
Type const &value, Comparator comp);
• Description:
– The first prototype: value is looked up using binary search in the range of elements
implied by the iterator range [first, last). The elements in the range must have
been sorted by the Type::operator<() function. True is returned if the element was
found, false otherwise.
– The second prototype: value is looked up using binary search in the range of elements
implied by the iterator range [first, last). The elements in the range must have
been sorted by the Comparator function object. True is returned if the element was
found, false otherwise.
• Example:
#include ..
#include ..
#include ..
#include ..
using namespace std;
int main()
{
string sarr[] =
{
"alpha", "bravo", "charley", "delta", "echo",
"foxtrot", "golf", "hotel"
};
string *last = sarr + sizeof(sarr) / sizeof(string);
bool result = binary_search(sarr, last, "foxtrot");
cout << (result ? "found " : "didn’t find ") << "foxtrot" << endl;
reverse(sarr, last); // reverse the order of elements
// binary search now fails:
result = binary_search(sarr, last, "foxtrot");
cout << (result ? "found " : "didn’t find ") << "foxtrot" << endl;
// ok when using appropriate
// comparator:
result = binary_search(sarr, last, "foxtrot", greater..());
cout << (result ? "found " : "didn’t find ") << "foxtrot" << endl;
return 0;
}
17.4. THE GENERIC ALGORITHMS 399
.r{}