我要做的就是检查向量中是否存在一个元素,这样我就可以处理每一种情况。
if ( item_present )
do_this();
else
do_that();
我要做的就是检查向量中是否存在一个元素,这样我就可以处理每一种情况。
if ( item_present )
do_this();
else
do_that();
当前回答
(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
其他回答
记住,如果你要做大量的查找,有STL容器会更好。我不知道你的应用程序是什么,但是像std::map这样的关联容器可能值得考虑。
vector是容器的选择,除非您有其他原因,按值查找就是这样一个原因。
我个人最近使用模板一次处理多种类型的容器,而不是只处理向量。我在网上找到了一个类似的例子(不记得在哪里了),所以功劳归于我从谁那里偷来的。这种特殊的模式似乎也可以处理原始数组。
template <typename Container, typename T = typename std::decay<decltype(*std::begin(std::declval<Container>()))>::type>
bool contains(Container && c, T v)
{
return std::find(std::begin(c), std::end(c), v) != std::end(c);
}
正如其他人所说,使用STL的find或find_if函数。但是如果你搜索的是非常大的向量,这会影响性能,你可能想要对你的向量排序,然后使用binary_search、lower_bound或upper_bound算法。
你也可以使用count。 它将返回向量中存在的项的数量。
int t=count(vec.begin(),vec.end(),item);
boost可以使用any_of_equal:
#include <boost/algorithm/cxx11/any_of.hpp>
bool item_present = boost::algorithm::any_of_equal(vector, element);