std::binary_search
Use case
Check if value exists in sorted range.
Explanation
Requires sorted range. Returns bool only. Much faster than find for large sorted datasets.
Time complexity: O(log n). Halves earch space each step. For 1M elements, only ~20 comparisons needed. See possible implementation.
Code
#include <algorithm>
#include <print>
#include <string>
#include <vector>
int main() {
std::vector<std::string> symbols = {"_helper", "_init", "_main", "_start"};
bool hasMain = std::binary_search(symbols.begin(), symbols.end(), "_main");
std::println("Symbol '_main' exists: {}", hasMain);
return 0;
}
Output
$ ./src/algorithms/build/std-binary_search
Symbol '_main' exists: true