我在哪里可以得到一个"有用" C ++二进制搜索算法?我在、可以得到、算法、有用

2023-09-11 01:47:18 作者:农村城市混血儿

我需要一个二进制搜索算法,它与C ++标准的容器,像兼容的的std :: binary_search的在标准库中的 <算法> 头,但不同的std :: binary_search的,我需要它返回一个指向在结果迭代器,而不是一个简单的布尔如果该元素存在,告诉我

I need a binary search algorithm that is compatible with the C++ standard containers, something like std::binary_search in the standard library's <algorithm> header, but unlike std::binary_search, I need it to return the iterator that points at the result, not a simple boolean telling me if the element exists

(在一个侧面说明,什么是地狱是当他们定义的binary_search的API标准委员会的想法!)

(On a side note, what the hell was the standard committee thinking when they defined the API for binary_search!!!)

编辑:在这里我主要担心的是,我需要一个二进制搜索的速度,所以虽然我可以找到与其他算法的数据,如下所述,我想利用我的资料已经排序以获得二进制搜索的好处,而不只是任何搜索

My main concern here is that I need the speed of a binary search, so although I can find the data with other algorithms, as mentioned below, I want to take advantage that my data is already sorted to get the benefits of a binary search, not just any search.

到目前为止LOWER_BOUND和UPPER_BOUND失败,因为如果数据丢失:

so far lower_bound and upper_bound fail, because if the datum is missing:

//lousy pseudo code
vector(1,2,3,4,6,7,8,9,0) //notice no 5
iter = lower_bound_or_upper_bound(start,end,5)
iter != 5 && iter !=end //not returning end as usual, instead it'll return 4 or 6

此外,我真怀疑LOWER_BOUND和UPPER_BOUND实现为binary_searches,因为他们的工作一样好未排序的数据,有没有办法提供,通过参数或政策信息。 确定首先由vividos提到,他们需要排序的数据,这意味着它们是二进制搜索,所以这个世界和好如初:)的

注意:我也蛮好用一种算法,不属于std命名空间只要其与​​集装箱兼容。喜欢说的boost ::或binary_search的东西

Note: I'm also fine using an algorithm that doesn't belong to the std namespace as long as its compatible with containers. Likes say boost::binary_search or something

推荐答案

有没有这样的功能,但可以使用的 的std :: LOWER_BOUND ,的 的std :: UPPER_BOUND 或std::equal_range.

There is no such functions, but you can write a simple one using std::lower_bound, std::upper_bound or std::equal_range.

一个简单的实现可能是

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
}

另一种解决方案是使用的std ::设为,这保证了元素的顺序,并提供了一​​种方法的迭代器查找(T键)返回一个迭代器给定的项目。但是,(如果你需要存储相同的元素多次为例)你的要求可能与使用一组兼容。

Another solution would be to use a std::set, which guarantees the ordering of the elements and provides a method iterator find(T key) that returns an iterator to the given item. However, your requirements might not be compatible with the use of a set (for example if you need to store the same element multiple times).