Binary search is a highly efficient way to find an item from a sorted collection of items. In C++, although the standard library provides the std::vector
and std::array
containers, std::deque
can also be used with binary search with a proper approach. Binary search works by repeatedly dividing the range of possible values in half until the target value is found or the range is exhausted.
Here is an example of how to perform a binary search using std::deque
:
#include <iostream>
#include <deque>
#include <algorithm>
int main() {
std::deque myDeque = {1, 3, 5, 7, 9, 11, 13, 15};
int target = 7;
auto it = std::lower_bound(myDeque.begin(), myDeque.end(), target);
if (it != myDeque.end() && *it == target) {
std::cout << "Element found: " << *it << 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?