C++:通过count和find判断vector中是否包含某个数据

vector本身没有提供可以检测某个数据是否在其中的成员方法,可以使用泛型方法count和find进行检查:

#include 
#include 
#include 
using namespace std;

int main()
{
	vector d{1, 2, 2, 2, 3, 4, 5};
	auto num = count(d.begin(), d.end(), 2);
	cout<<"has 2 for "<

运行程序输出:

has 2 for 3 times

find data 3

需要说明的是,count需要计数,所以会遍历整个vector,所以效率会低一些。 

你可能感兴趣的:(C/C++,c++)