C++ 如何确定一个项目是否存在于 std::vector 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/571394/
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 16:00:23  来源:igfitidea点击:

How to find out if an item is present in a std::vector?

c++vectorstd

提问by Joan Venge

All I want to do is to check whether an element exists in the vector or not, so I can deal with each case.

我想要做的就是检查向量中是否存在元素,以便我可以处理每种情况。

if ( item_present )
   do_this();
else
   do_that();

回答by MSN

You can use std::findfrom <algorithm>:

您可以使用std::find<algorithm>

#include <vector>
vector<int> vec; 
//can have other data types instead of int but must same datatype as item 
std::find(vec.begin(), vec.end(), item) != vec.end()

This returns a bool (trueif present, falseotherwise). With your example:

这将返回一个布尔值(true如果存在,false否则)。以你的例子:

#include <algorithm>
#include <vector>

if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
   do_this();
else
   do_that();

回答by Brian Neal

As others have said, use the STL findor find_iffunctions. But if you are searching in very large vectors and this impacts performance, you may want to sort your vector and then use the binary_search, lower_bound, or upper_boundalgorithms.

正如其他人所说,使用 STLfindfind_if函数。但是,如果你在非常大的矢量搜索,这会影响性能,您可能要排序的载体,然后使用binary_searchlower_boundupper_bound算法。

回答by m-sharp

Use find from the algorithm header of stl.I've illustrated its use with int type. You can use any type you like as long as you can compare for equality (overload == if you need to for your custom class).

使用 stl 的算法头文件中的 find。我已经用 int 类型说明了它的使用。您可以使用任何您喜欢的类型,只要您可以比较相等性(如果您的自定义类需要,则重载 ==)。

#include <algorithm>
#include <vector>

using namespace std;
int main()
{   
    typedef vector<int> IntContainer;
    typedef IntContainer::iterator IntIterator;

    IntContainer vw;

    //...

    // find 5
    IntIterator i = find(vw.begin(), vw.end(), 5);

    if (i != vw.end()) {
        // found it
    } else {
        // doesn't exist
    }

    return 0;
}

回答by spiralmoon

If your vector is not ordered, use the approach MSN suggested:

如果您的向量未排序,请使用 MSN 建议的方法:

if(std::find(vector.begin(), vector.end(), item)!=vector.end()){
      // Found the item
}

If your vector is ordered, use binary_search method Brian Neal suggested:

如果您的向量已排序,请使用 binary_search 方法 Brian Neal 建议:

if(binary_search(vector.begin(), vector.end(), item)){
     // Found the item
}

binary search yields O(log n) worst-case performance, which is way more efficient than the first approach. In order to use binary search, you may use qsort to sort the vector first to guarantee it is ordered.

二分搜索产生 O(log n) 最坏情况的性能,这比第一种方法更有效。为了使用二分搜索,您可以先使用 qsort 对向量进行排序以保证它是有序的。

回答by Andy Krouwel

I use something like this...

我用这样的东西...

#include <algorithm>


template <typename T> 
const bool Contains( std::vector<T>& Vec, const T& Element ) 
{
    if (std::find(Vec.begin(), Vec.end(), Element) != Vec.end())
        return true;

    return false;
}

if (Contains(vector,item))
   blah
else
   blah

...as that way it's actually clear and readable. (Obviously you can reuse the template in multiple places).

...这样它实际上是清晰易读的。(显然您可以在多个地方重复使用该模板)。

回答by Deqing

In C++11 you can use any_of. For example if it is a vector<string> v;then:

在 C++11 中,您可以使用any_of. 例如,如果它是一个vector<string> v;then:

if (any_of(v.begin(), v.end(), bind(equal_to<string>(), _1, item)))
   do_this();
else
   do_that();

Alternatively, use a lambda:

或者,使用 lambda:

if (any_of(v.begin(), v.end(), [&](const std::string& elem) { return elem == item; }))
   do_this();
else
   do_that();

回答by Martin Broadhurst

Here's a function that will work for any Container:

这是一个适用于任何容器的函数:

template <class Container> 
const bool contains(const Container& container, const typename Container::value_type& element) 
{
    return std::find(container.begin(), container.end(), element) != container.end();
}

Note that you can get away with 1 template parameter because you can extract the value_typefrom the Container. You need the typenamebecause Container::value_typeis a dependent name.

请注意,您可以使用 1 个模板参数,因为您可以value_type从容器中提取。您需要typename因为Container::value_type是一个从属名称

回答by David Thornley

Bear in mind that, if you're going to be doing a lot of lookups, there are STL containers that are better for that. I don't know what your application is, but associative containers like std::map may be worth considering.

请记住,如果您要进行大量查找,则有更好的 STL 容器。我不知道你的应用程序是什么,但像 std::map 这样的关联容器可能值得考虑。

std::vector is the container of choice unless you have a reason for another, and lookups by value can be such a reason.

std::vector 是首选容器,除非您有另一个原因,而按值查找可能就是这样一个原因。

回答by Frank

Use the STL findfunction.

使用 STL查找功能。

Keep in mind that there is also a find_iffunction, which you can use if your search is more complex, i.e. if you're not just looking for an element, but, for example, want see if there is an element that fulfills a certain condition, for example, a string that starts with "abc". (find_ifwould give you an iterator that points to the first such element).

请记住,还有一个find_if函数,如果您的搜索更复杂,您可以使用该函数,即如果您不仅要查找某个元素,而且,例如,想要查看是否有一个元素满足某个特定要求条件,例如,以“abc”开头的字符串。(find_if会给你一个指向第一个这样的元素的迭代器)。

回答by Mikhail

With boost you can use any_of_equal:

随着提升,你可以使用any_of_equal

#include <boost/algorithm/cxx11/any_of.hpp>

bool item_present = boost::algorithm::any_of_equal(vector, element);