#include"iostream"
#include"string"
#include"set"
using namespace std ;
// 什么是set/multiset容器?
// set/multiset容器的底层原理是由二叉树实现。
// 对set遍历的时候会有序输出。
// set容器和multiset的区别?
// set不允许数据重复,multiset相反。
// 生成数据
void genSet(set<int> &st)
{
for (int i=20;i>0;i--)
{
st.insert(i);
}
}
// 输出数据
void printSet(set<int> &st)
{
for(set<int>::iterator it = st.begin();it!=st.end();it++)
{
cout<<*it<<'\t';
}
cout<<endl;
}
// 构造器
void constructor()
{
// 默认构造
set<int> st;
genSet(st);
// 拷贝构造
set<int>st2(st);
printSet(st);
}
// set的大小和交换
void sizeAndSwap()
{
set<int> st;
genSet(st);
// 得到st的大小
cout<<st.size()<<endl;
set<int> st2;
st2.insert(-1);
st2.insert(-2);
st2.insert(-3);
st2.insert(-4);
st2.insert(-5);
// 交换st和st2
st.swap(st2);
printSet(st);
printSet(st2);
// 返回set是否为空
cout<<st.empty()<<endl;
}
void insertAndErase()
{
set<int> st;
// 插入元素
st.insert(10);
// 删除元素
st.erase(10);
// 清除所有元素
st.clear();
}
void findAndCount()
{
set<int> st;
genSet(st);
// 查找1这个元素的迭代器
set<int>::iterator it = st.find(1);
cout<<*it<<endl;
// 统计元素1有多少个
cout<<st.count(1)<<endl;
}
// 自定义数据类型的排序(指定set的排序规则)
class Person{
public:
Person(string name,int age)
{
this->age=age;
this->name =name;
}
string name;
int age;
};
// 定义排序规则
class comparePerson{
public :
bool operator()(const Person &p1,const Person &p2) const
{
return p1.age>p2.age;
}
};
void classSort()
{
// 创建set容器
set<Person,comparePerson> s;
// 创建数据
Person p1("Gloy",24);
Person p2("Golay",42);
Person p3("Gaty",32);
Person p4("Gocucy",12);
Person p5("Staycatlod",43);
// 插入数据
s.insert(p1);
s.insert(p2);
s.insert(p3);
s.insert(p4);
s.insert(p5);
// 输出数据
for(set<Person,comparePerson>::iterator it = s.begin();it!=s.end();it++)
{
cout<<it->age<<it->name<<endl;
}
}
int main()
{
classSort();
return 0;
}
C++ Set容器的概念和用法
最新推荐文章于 2024-08-18 21:07:18 发布