vector本身没有提供可以检测某个数据是否在其中的成员方法,可以使用泛型方法count和find进行检查:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> d{1, 2, 2, 2, 3, 4, 5};
auto num = count(d.begin(), d.end(), 2);
cout<<"has 2 for "<<num<<" times"<<endl;
auto ifFind = find(d.begin(), d.end(), 3);
if(ifFind != d.end())
{
cout<<"find data 3"<<endl;
}
return 0;
}
运行程序输出:
has 2 for 3 times
find data 3
需要说明的是,count需要计数,所以会遍历整个vector,所以效率会低一些。