我要做的就是检查向量中是否存在一个元素,这样我就可以处理每一种情况。
if ( item_present )
do_this();
else
do_that();
我要做的就是检查向量中是否存在一个元素,这样我就可以处理每一种情况。
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();
其他回答
正如其他人所说,使用STL的find或find_if函数。但是如果你搜索的是非常大的向量,这会影响性能,你可能想要对你的向量排序,然后使用binary_search、lower_bound或upper_bound算法。
如果你想在向量中找到一个字符串:
struct isEqual
{
isEqual(const std::string& s): m_s(s)
{}
bool operator()(OIDV* l)
{
return l->oid == m_s;
}
std::string m_s;
};
struct OIDV
{
string oid;
//else
};
VecOidv::iterator itFind = find_if(vecOidv.begin(), vecOidv.end(), isEqual(szTmp));
从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;
}
在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();
你可以使用find函数,在std命名空间中找到,即std::find。向std::find函数传递要搜索的向量的begin迭代器和end迭代器,以及要查找的元素,并将结果迭代器与向量的结束迭代器进行比较,以查看它们是否匹配。
std::find(vector.begin(), vector.end(), item) != vector.end()
您还可以解除对该迭代器的引用,并像其他迭代器一样正常使用它。