Binary Search Algorithm with Iterator Return for C Containers
The STL's std::binary_search algorithm efficiently identifies the presence of an element within a sorted container, but it only returns a boolean value. For scenarios where the exact location of the element is crucial, you may require an iterator-based search algorithm.
To address this need, the following custom binary search algorithm can be employed:
<code class="cpp">template<class Iter, class T> Iter binary_find(Iter begin, Iter end, T val) { // Finds the lower bound in at most log(last - first) + 1 comparisons Iter i = std::lower_bound(begin, end, val); if (i != end && !(val < *i)) return i; // found else return end; // not found }</code>
This algorithm utilizes std::lower_bound to find the insertion point of the value in the container (if it were to be inserted). If the value is present, the iterator is returned; otherwise, the end iterator is returned. This approach ensures both speed and precision
You can also consider using a std::set, which provides an iterator find(T key) function that directly returns the iterator pointing to the given item. However, this may not be suitable for cases where duplicate elements are required.
The above is the detailed content of How to Implement an Iterator-Based Binary Search Algorithm for Sorted C Containers?. For more information, please follow other related articles on the PHP Chinese website!