如何在排序的 C++ 向量中找到一个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18994602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:24:40  来源:igfitidea点击:

How to find a value in a sorted C++ vector?

c++sortingsearchvectorfind

提问by user2813274

I have looked at findand binary_search, but find doesn't take advantage of the fact that the vector is sorted, and binary_search only returns a true or false, not where it found the value. Is there any function that can give me the best of both worlds?

我看过findbinary_search,但 find 没有利用向量已排序的事实,并且 binary_search 只返回 true 或 false,而不是在它找到值的地方。有什么功能可以让我两全其美?

回答by Steve Howard

std::lower_boundwill do that for you. It's in the equivalent-behavior section at the top for binary_search.

std::lower_bound将为您做到这一点。它位于 binary_search 顶部的等效行为部分。

回答by paxdiablo

There is a method, std::equal_range, which will give you a pair containing the lower and upper bound of the subset holding the desired value. If both of those items in the pair are identical, then the value you were looking for doesn't exist.

有一种方法,std::equal_range,它将为您提供一对,其中包含保存所需值的子集的下限和上限。如果这对中的这两个项目相同,则您要查找的值不存在。

回答by Gabriel Schreiber

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;
}