function binary searching c++ code example
Example 1: how to do binary search in c++ using STL
#include<bits/stdc++.h>
usind namespace std;
int main()
{
int arr[]={10,2,34,2,5,4,1};
sort(arr,arr+7);
binary_search(arr,arr+7,10);
binary_search(arr,arr+7,3);
return 0;
}
Example 2: c++ binary search
#include <algorithm>
#include <vector>
bool binarySearchVector(const std::vector<int>& vector,
int target) {
return std::binary_search(vector.cbegin(), vector.cend(), target);
}
#include <iostream>
int main()
{
std::vector<int> haystack {1, 3, 4, 5, 9};
std::vector<int> needles {1, 2, 3};
for (auto needle : needles) {
std::cout << "Searching for " << needle << std::endl;
if (binarySearchVector(haystack, needle)) {
std::cout << "Found " << needle << std::endl;
} else {
std::cout << "no dice!" << std::endl;
}
}
}