Binary search is an efficient search algorithm that finds the position of a target value within a sorted array. In C++17 and later, you can utilize `std::span` to represent a view over a contiguous sequence of elements. Below is an example of how to implement binary search using `std::span`.
#include
#include
#include
int binarySearch(std::span arr, int target) {
auto it = std::lower_bound(arr.begin(), arr.end(), target);
if (it != arr.end() && *it == target) {
return std::distance(arr.begin(), it);
}
return -1; // Target not found
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::span spanArr(arr, 10);
int target = 7;
int result = binarySearch(spanArr, target);
if (result != -1) {
std::cout << "Element found at index: " << result << std::endl;
} else {
std::cout << "Element not found!" << std::endl;
}
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?