Home > Backend Development > C++ > How to Implement an Iterator-Based Binary Search Algorithm for Sorted C Containers?

How to Implement an Iterator-Based Binary Search Algorithm for Sorted C Containers?

Mary-Kate Olsen
Release: 2024-10-24 01:30:01
Original
536 people have browsed it

How to Implement an Iterator-Based Binary Search Algorithm for Sorted C   Containers?

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 &amp;&amp; !(val < *i))
        return i; // found
    else
        return end; // not found
}</code>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template