Answers for "binary_search function in c++"

C++
1

c++ binary search

//requires header <algorithm> for std::binary_search
#include <algorithm>
#include <vector>

bool binarySearchVector(const std::vector<int>& vector,
                       	int target) {
  //this line does all binary searching
  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;
        }
    }
}
Posted by: Guest on January-24-2021

Browse Popular Code Answers by Language