https://en.cppreference.com/w/cpp/algorithm/binary_search
template <class ForwardIt, class T>
bool binary_search(ForwardIt first, ForwardIt last, const T& value); // (1)
template <class ForwardIt, class T, class Compare>
bool binary_search(ForwardIt first, ForwardIt last, const T& value,
Compare comp); // (2)
first - last 까지 value 가 있나 찾기
있으면 true, 없으면 false
#include <algorithm>
#include <iostream>
#include <vector>
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 << '\\n';
if (std::binary_search(haystack.begin(), haystack.end(), needle)) {
std::cout << "Found " << needle << '\\n';
} else {
std::cout << "no dice!\\n";
}
}
}
실행 결과
Searching for 1
Found 1
Searching for 2
no dice!
Searching for 3
Found 3