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

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

当前回答

使用STL的find函数。

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

其他回答

boost可以使用any_of_equal:

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

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

你可以使用std::find from <algorithm>:

#include <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()

这将返回找到的第一个元素的迭代器。如果不存在,则返回一个指向倒数一的迭代器。用你的例子:

#include <algorithm>
#include <vector>

if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
   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;
    }

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

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