如何以最有效的方式在排序的C++向量中查找值?

avwztpqn  于 2023-03-05  发布在  其他
关注(0)|答案(4)|浏览(130)

我已经研究了findbinary_search,但是find没有利用向量被排序的事实,binary_search只返回true或false,而不返回找到值的位置,有没有什么函数可以给予我两全其美呢?

jm2pwxwz

jm2pwxwz1#

可以使用find在时间O内定位任何容器中的特定元素(N)。使用向量,您可以进行随机访问并利用下界(log 2(N))、upper_bound或equal_range类的标准算法。std::lower_bound将为您完成这些操作。它位于binary_search顶部的等效行为部分。但是,binary_search的实用性仅限于yes和no两个答案(可能命名需要在C++的未来版本中改进;binary_in()中的函数)。

rnmwe5a2

rnmwe5a22#

有一个方法std::equal_range,它会给予你一个包含所需值的子集的下限和上限的对,如果对中的这两项相同,那么你要找的值不存在。

jutyujz0

jutyujz03#

template<class T, class U>
bool contains(const std::vector<T>& container, const U& v)
{
    auto it = std::lower_bound(
        container.begin(),
        container.end(),
        v,
        [](const T& l, const U& r){ return l < r; });
    return it != container.end() && *it == v;
}
igsr9ssn

igsr9ssn4#

你可以使用下面的方法来检查元素'x'是否出现在排序向量'vec'中,并在O(log n)时间复杂度内一次性打印出它的索引。

int ind = lower_bound(vec.begin(), vec.end(), x) - vec.begin();

if(ind != vec.size() && vec[ind] == x)
    cout << "Found at: " << ind;  
else
    cout << "Not found";

相关问题