#include<iostream>
#include<set>
using namespace std;
void test_set()
{
//四种构造函数形式举例
set<int> Myset1;
int Myint2[] = {2,4,6,8,10};
set<int> Myset2(Myint2,Myint2 + 5);
set<int> Myset3(Myset2);
set<int> Myset4(Myset2.begin(),Myset2.end());
//插入数据
for (int i=1; i<=5; ++i) //插入1 2 3 4 5
Myset1.insert(i);
int Myint3[] = {3,15,9,6,12};//尽管数组本身,但插入set之后是有序的,且注意对于重复元素(6)是不能重复插入的
Myset3.insert(Myint3,Myint3+5);
//查找操作
set<int>::iterator itr;//迭代器
itr = Myset1.find(3);//查找2
if(itr!= Myset1.end())
cout<<"在Myset1找到元素3!"<<endl;
else
cout<<"在Myset1找不到元素3!"<<endl;
//元素遍历,两种形式
cout<<"\nMyset1中元素内容如下:"<<endl;
for(itr = Myset1.begin();itr!=Myset1.end();itr++)
cout<<*itr<<" ";
cout<<"\nMyset2中元素内容如下:"<<endl;
for(itr = Myset2.begin();itr!=Myset2.end();itr++)
cout<<*itr<<" ";
cout<<"\nMyset3中元素内容如下:"<<endl;
for(itr = Myset3.begin();itr!=Myset3.end();itr++)
cout<<*itr<<" ";
cout<<"\nMyset4中元素内容如下:"<<endl;
itr = Myset4.begin();
while(itr != Myset4.end())
cout<<*itr ++ << " ";
//逆向遍历Myset4
cout<<"\nMyset4逆向遍历结果如下:"<<endl;
set<int>::reverse_iterator itr2 = Myset4.rbegin();
while(itr2 != Myset4.rend())
cout<<*itr2++ << " ";
cout<<endl;
//删除操作
for(int i = 1;i<=5;i++)
Myset3.erase(i*2);
cout<<"\nMyset3删除元素之后内容如下:"<<endl;
for(itr = Myset3.begin();itr!=Myset3.end();itr++)
cout<<*itr<<" ";
//或者用itr删除,
itr = Myset4.begin();
itr ++;//此时itr指向4
Myset4.erase(itr);
cout<<"\nMyset4删除元素之后内容如下:"<<endl;
for(itr = Myset4.begin();itr!=Myset4.end();itr++)
cout<<*itr<<" ";
itr = Myset4.find(6);
Myset4.erase(itr,Myset4.end());
cout<<"\nMyset4再次删除元素之后内容如下:"<<endl;
for(itr = Myset4.begin();itr!=Myset4.end();itr++)
cout<<*itr<<" ";
//交换
Myset1.swap(Myset2);
cout<<"Myset1与Myset2进行交换"<<endl;
cout<<"\n交换后Myset1内容如下:"<<endl;
for(itr = Myset1.begin();itr!=Myset1.end();itr++)
cout<<*itr<<" ";
cout<<"\n交换后Myset2内容如下:"<<endl;
for(itr = Myset2.begin();itr!=Myset2.end();itr++)
cout<<*itr<<" ";
cout<<endl;
//清除与求大小
cout<<"\nMyset1大小为:"<<Myset1.size()<<endl;
Myset1.clear();
cout<<"clear()清除Myset1的所有元素后大小为"<<Myset1.size()<<endl;
}
set【Template】
最新推荐文章于 2023-03-23 23:24:54 发布