algorithm - STL C++

binary_search()

Declaration

template <class ForwardIterator, class X>
ForwardIterator binary_search(
	ForwardIterator qFirst,
	ForwardIterator qLast,
	const X& kxrTarget
);

Description

This function searches the ordered entries from "qFirst" to the one before "qLast" for the target value "kxrTarget."

Header Include

#include <algorithm>

Overloads

template <class ForwardIterator, class X, class BinaryPredicate>
ForwardIterator binary_search(
	ForwardIterator qFirst,
	ForwardIterator qLast,
	const X& kxrTarget,
	BinaryPredicate qLessThan
);

Example

#include <iostream>
#include <vector>
#include <algorithm>

// Comparison function
bool LessThan(int iInt1, int iInt2) {
	return (iInt1 < iInt2);
}

int main()
{
	using namespace std;

	// Create a vector instance and add entries in order
	vector<int> qV;
	qV.push_back(3);
	qV.push_back(5);
	qV.push_back(6);
	qV.push_back(9);
	qV.push_back(11);
	qV.push_back(17);
	qV.push_back(65);
	qV.push_back(92);

	// Search for the values 4 and 17
	int iSearch1 = 4;
	bool bFound1 = binary_search(qV.begin(), qV.end(), iSearch1);
	int iSearch2 = 17;
	bool bFound2 = binary_search(qV.begin(), qV.end(), iSearch2);

	cout << "The value " << iSearch1 <<
		(bFound1 ? " was ": " was not ") << "found." << endl;
	cout << "The value " << iSearch2 <<
		(bFound2 ? " was ": " was not ") << "found." << endl;

	// Perfom another search for 11 and 34, using LessThan()
	iSearch1 = 11;
	bFound1 = binary_search(qV.begin(), qV.end(), iSearch1, LessThan);
	iSearch2 = 30;
	bFound2 = binary_search(qV.begin(), qV.end(), iSearch2, LessThan);

	cout << "The value " << iSearch1 <<
		(bFound1 ? " was ": " was not ") << "found." << endl;
	cout << "The value " << iSearch2 <<
		(bFound2 ? " was ": " was not ") << "found." << endl;

	cin.get();
	return 0;
}

Output

binary_search() Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.