C++:vector容器是否包含给定元素

vector容器是否包含给定元素

C++中检查vector是否包含给定元素的几种方式

std::count

最简单的方式是对vector中的指定元素进行计数,如果count不为零,表示该元素存在

#include 
#include 
#include 

int main()
{
	std::vector<int> v = { 1, 20, 2, 6, 3, 7 };
	int key = 6;

	if (std::count(v.begin(), v.end(), key))
		std::cout << "Element found";
	else
		std::cout << "Element not found";

	return 0;
}

std::find

相比第一种方式,std::find()算法能够更快速的查找给定范围内的值,因为std::count()会遍历整个容器以获得元素计数,而find()在找到匹配元素后就立即停止搜索

#include 
#include 
#include 

int main()
{
	std::vector<int> v = { 1, 20, 2, 6, 3, 7 };
	int key = 6;

	if (std::find(v.begin(), v.end(), key) != v.end())
		std::cout << "Element found";
	else
		std::cout << "Element not found";

	return 0;
}

你可能感兴趣的:(编程,c++,开发语言)