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

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

当前回答

在c++ 11中,你可以使用any_of。例如,如果它是一个向量<字符串> v;然后:

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

或者,使用lambda:

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

其他回答

从c++ 20开始,使用range (#include <ranges>)

    //SAMPLE DATA
    std::vector<int> vecOfElements = { 2,4,6,8 };

    //DO SOMETHING IF 8 IN VECTOR
    if (std::ranges::find(vecOfElements, 8) != vecOfElements.end())
    {
        std::cout << "DO SOMETHING" << std::endl;
    }

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

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

注意,您可以使用一个模板形参,因为您可以从Container中提取value_type。您需要typename,因为Container::value_type是一个依赖名称。

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

vector是容器的选择,除非您有其他原因,按值查找就是这样一个原因。

(c++ 17及以上):

还可以使用std::search吗

这对于搜索元素序列也很有用。

#include <algorithm>
#include <iostream>
#include <vector>

template <typename Container>
bool search_vector(const Container& vec, const Container& searchvec)
{
    return std::search(vec.begin(), vec.end(), searchvec.begin(), searchvec.end()) != vec.end();
}

int main()
{
     std::vector<int> v = {2,4,6,8};

     //THIS WORKS. SEARCHING ONLY ONE ELEMENT.
     std::vector<int> searchVector1 = {2};
     if(search_vector(v,searchVector1))
         std::cout<<"searchVector1 found"<<std::endl;
     else
         std::cout<<"searchVector1 not found"<<std::endl;

     //THIS WORKS, AS THE ELEMENTS ARE SEQUENTIAL.
     std::vector<int> searchVector2 = {6,8};
     if(search_vector(v,searchVector2))
         std::cout<<"searchVector2 found"<<std::endl;
     else
         std::cout<<"searchVector2 not found"<<std::endl;

     //THIS WILL NOT WORK, AS THE ELEMENTS ARE NOT SEQUENTIAL.
     std::vector<int> searchVector3 = {8,6};
     if(search_vector(v,searchVector3))
         std::cout<<"searchVector3 found"<<std::endl;
     else
         std::cout<<"searchVector3 not found"<<std::endl;
}

此外,还可以灵活地传递一些搜索算法。请参考这里。

https://en.cppreference.com/w/cpp/algorithm/search

如果你的向量是无序的,使用MSN建议的方法:

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

如果你的向量是有序的,使用binary_search方法Brian Neal建议:

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

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