zl程序教程

您现在的位置是:首页 >  其他

当前栏目

set容器的查找和统计

2023-09-14 09:02:34 时间

查找和统计

在这里插入图片描述

#include<iostream>
using namespace std;
#include<set>
void p(set<int>& s)
{
	for (set<int>::iterator it = s.begin(); it != s.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}
void test()
{
	set<int> s1 = {1,2,3};
	//插入数据,只有用insert方式
	s1.insert(4);
	s1.insert(6);
	s1.insert(6);
	s1.insert(5);
	p(s1);
   //查找某一元素是否存在,存在就返回其迭代器,否则返回set.end()
	set<int>::iterator it=s1.find(3);
	if (it != s1.end())
		cout << "该元素: " << *it << endl;
	else
		cout << "未找到该元素" << endl;
	//统计某一个元素的个数
	//对于set而言,结果只有0和1
	int num = 0;
	num = s1.count(3);
	cout << "元素3的个数为:" << num << endl;
}
int main()
{
	test();
	system("pause");
	return 0;
}

在这里插入图片描述

总结:
在这里插入图片描述