C++ Programming

STL Binary Search

C plus plus example for STL Binary search

12/9/2019
0 views
stl-binary-search.cppCPP
#include<iostream>
#include<algorithm>
using namespace std;

template <class t>
class b_search {
	int size;
	t *list;
	public:
		b_search(t *data, int length) {
			list = data;
			size = length;
		}

		void find(t item) {

			/* Search data using STL 'binary_search()' */
			if (binary_search(list, list+size, item))
				cout << item << " found!" << endl;
			else
				cout << item << " not found!" << endl;
		}
};

int main() {

	/* Binary search using integer */
	int iArray[] = {10,20,30,40,50,60,70,80,90};
	int iSize = (sizeof((iArray))/sizeof((iArray[0])));
	b_search<int> intSearch(iArray, iSize);	
	intSearch.find(30);

	/* Binary search using float */
	float fArray[] = {1.22,2.31,3.50,4.55,5.23,6.70,7.11,8.32,9.12};
	int fSize = (sizeof((fArray))/sizeof((fArray[0])));
	b_search<float> floatSearch(fArray, fSize);	
	floatSearch.find(3);

	/* Binary search using string */
	string sArray[] = {"be","c++","fun","find","go","java","search","to"};
	int sSize = (sizeof((fArray))/sizeof((fArray[0])));
	b_search<string> stringSearch(sArray, sSize);	
	stringSearch.find("fun");

	return 0;
}



/* Output */
30 found!
3 not found!
fun found!
cppc plus plusSTL Binary searchstandard template library

Loading comments...

Related Examples

Deliver breaking news, insightful commentary, and exclusive reports.

Targeting readers who rely on our platform to stay ahead of the curve.

Contact Us: benzingaheadlines@gmail.com