#include<iostream>
#include<set>
#include<string>
using namespace std;
//关联式容器,底层是二叉树,插入时自动排序
//set不允许有重复的元素
//multiset允许有重复的元素
//遍历
void printSet(set<int>&s)
{
for (set<int>::iterator it = s.begin(); it != s.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
//构造函数
void test01()
{
//默认构造
set<int>s1;
//拷贝构造
set<int>s2(s1);
//赋值
set<int>s3 = s2;
}
//大小和交换
void test02()
{
set<int>s1 = { 1,2,3,4,5,6 };
set<int>s2 = { 2,3,4,5,6,7 };
//返回容器元素的数目
s1.size();
//判断是否为空
s1.empty();
//交换
s1.swap(s2);
printSet(s1);
printSet(s2);
}
//插入和删除
void test03()
{
set<int>s1;
//插入
s1.insert(10);
//清除所以元素
s1.clear();
s1.insert(10);
s1.insert(20);
s1.insert(30);
s1.insert(40);
s1.insert(50);
//删除迭代器所指元素,返回下一元素的迭代器
s1.erase(s1.erase(s1.begin())); //可嵌套使用
printSet(s1);
//删除容器中值为elem的元素
s1.erase(50);
printSet(s1);
//删除区间
s1.erase(s1.begin(), s1.end());
printSet(s1);
}
//查找和统计
void test04()
{
multiset<int>ms1 = { 30,40,80,97,55,66,30,40,45 };
//存在则返回当前元素迭代器,不存在则返回end迭代器
ms1.find(30);
//查找元素有几个
int num = ms1.count(30);
cout << num << endl;
}
//set和multiset的区别
//set插入数据时会返回插入结果
//multiset允许插入重复的值,不会返回插入结果
void test05()
{
set<int>s1;
pair<set<int>::iterator, bool> ret = s1.insert(10);
if (ret.second)
{
cout << "插入成功" << endl;
}
else
{
cout << "插入失败" << endl;
}
}
//pair对组创建
void test06()
{
pair<int, char> p(10, 97);
cout << p.first << " " << p.second << endl;
pair<char, int> p1 = make_pair('a', 10);
cout << p1.first << " " << p1.second << endl;
}
//排序规则
class sortSet //仿函数
{
public:
bool operator()(int v1,int v2) //重载()
{
return v1 > v2;
}
};
void test07()
{
set<int>s1 = { 10,20,30,40,50,60,70 };
printSet(s1);
//调用制定的规则
set<int, sortSet>s2;
s2 = { 1,3,5,6,4,8,2,9 };
for (set<int,sortSet>::iterator it = s2.begin(); it != s2.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
//排序自定义的类型
class Person
{
public:
Person(string name, int age)
{
m_name = name;
m_age = age;
}
string m_name;
int m_age;
};
//二元谓词
class comparePerson
{
public:
bool operator()(const Person &v1, const Person &v2)
{
return v1.m_age > v2.m_age;
}
};
void test08()
{
set<Person,comparePerson>s;
Person p1("张飞", 18);
Person p2("关羽", 22);
Person p3("刘备", 20);
s.insert(p1);
s.insert(p2);
s.insert(p3);
for (set<Person>::iterator it = s.begin(); it != s.end(); it++)
{
cout << "姓名:" << it->m_name << " 年龄:" << it->m_age << endl;
}
}
int main()
{
test08();
system("pause");
return 0;
}