您好,欢迎来到尔游网。
搜索
您的当前位置:首页C++:vector容器是否包含给定元素

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

来源:尔游网

vector容器是否包含给定元素

std::count

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

#include <iostream>
#include <vector>
#include <algorithm>

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 <iostream>
#include <vector>
#include <algorithm>

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;
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- axer.cn 版权所有 湘ICP备2023022495号-12

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务