[C++]-set 集合

set集合用于存放一组无重复的元素。由于集合本身是有序的,所以可以高效地查找指定元素,也可以方便地得到指定大小范围地元素在容器中所处区间。

代码

#include<iostream>
#include<set>
using namespace std;

template<typename T>
inline void print_set(T s) // 定义该函数用于打印集合内容 
{
	for(typename T::iterator it = s.begin(); it!=s.end(); ++it)
		cout<<*it<<" "; cout<<endl<<endl;
}

int main()
{
	cout << "-----定义和初始化-----\n"; 
	int a[] = {3,2,1,5,4};
	// 定义一个集合,并初始化将数组a中的元素拷贝到集合中,默认是小于比较器less<int>(升序)
	set<int> seta(a, a+5);  
	a[2] = 22; // 修改a数组中的元素值,集合seta不会发生改变 
	print_set(seta);
	
	// 设置setb为大于比较器greater<int>(降序),初始化将seta的元素考北到setb中 
	set<int, greater<int> > setb(seta.begin(), seta.end()); 
	print_set(setb);
	
	cout << "----- 插入操作-----\n"; 
	set<int> setc;
	setc.insert(1); // insert()函数直接用于插入元素
	setc.insert(++setc.begin(), 0); // 指定位置插入元素3 
	pair<set<int>::iterator, bool> r1 = setc.insert(22); // insert()函数返回值为二元组
	pair<set<int>::iterator, bool> r2 = setc.insert(22); // 第二插入22不会成功
	// 二元组第一个元素是插入位置的迭代器,第二个元素是插入成功与否的标志
	// 成功插入返回true,失败返回false 
	cout << "r1:" << *r1.first << " " << r1.second << endl;
	// 第二次插入22会失败,则r2.first就是集合中已存在的22的位置的迭代器 
	cout << "r2:" << *r2.first << " " << r2.second << endl; 
	int b[] = {5,6,7};
	setc.insert(b+1, b+3); // b数组的后两个元素插入setc中 
	print_set(setc);
	
	cout << "----- 删除操作-----\n"; 
	int c[] = {1,2,3,4,5}; 
	set<int> setd(c, c+5);
	setd.erase(4); // 删除元素4
	setd.erase(++setd.begin()); // 删除第二个元素 
	print_set(setd);
	set<int> sete(c, c+5);
	set<int>::iterator ita = sete.begin();
	set<int>::iterator itb = --(--sete.end());
	sete.erase(ita, itb); // 删除区间[ita, itb)之间的元素 
	print_set(sete);
	sete.clear(); // 清空集合 
	if(sete.empty()) // 判空 
		cout << "集合已空" << endl << endl;
	
	cout << "----- 查找操作-----\n"; 
	int d[] = {1,2,3,4,5};
	set<int> setf(d, d+5);
	if(setf.find(3) != setf.end()) // 存在该元素,返回对应的迭代器 
		cout << "3在setf中" << " " << *setf.find(3) << endl;
	if(setf.find(7) == setf.end()) // 不存在该元素,返回setf.end() 
		cout << "不存在该元素\n" << endl; 
	
	cout << "----- 基于键的查找-----\n"; 
	int e[] = {2,3,1,5,4};
	set<int> setg(e, e+5);
	set<int>::iterator it1, it2;
	it1 = setg.lower_bound(3); cout << *it1 <<endl; // 第一个键值不小于3的元素的迭代器 
	it2 = setg.upper_bound(3); cout << *it2 <<endl; // 第一个键值大于3的元素的迭代器 
	cout << setg.count(2) << " " << setg.count(9) << endl; // 获取集合中元素2和9的个数 
	pair<set<int>::iterator, set<int>::iterator> pa;
	pa = setg.equal_range(2); // 获取一个区间,该区间(左闭右开)包含所有元素2
	for(set<int>::iterator it = pa.first; it != pa.second; ++it)
		cout << *it << " "; 	
}

运行结果

-----定义和初始化-----
1 2 3 4 5 

5 4 3 2 1 

----- 插入操作-----
r1:22 1
r2:22 0
0 1 6 7 22 

----- 删除操作-----
1 3 5 

4 5 

集合已空

----- 查找操作-----
3在setf中 3
不存在该元素

----- 基于键的查找-----
3
4
1 0
2 

感谢

posted @ 2020-07-31 15:30  世纪小小孟  阅读(317)  评论(0编辑  收藏  举报