**
set容器
**
所有元素都会在插入时自动被排序
本质:
set/multiset属于关联式容器,底层结构是用二叉树实现
set和multiset的区别:
set不允许容器中有重复的元素
multiset允许容器中有重复的元素
set容器的构造和赋值
构造
set 默认构造
set<const set &st> 拷贝构造函数
赋值
set& operator=(const set &st) 重载等号操作符
示例代码
//set构造和赋值
void test101()
{
set<int>s1;
//插入数据只有insert方式
s1.insert(10);
s1.insert(20);
s1.insert(30);
s1.insert(40);
//set容器特点:
//所有元素插入时自动排序
//不允许插入重复值
printSet(s1);
//拷贝构造
set<int>s2(s1);
printSet(s2);
set<int>s3;
s3 = s1;
printSet(s3);
}
大小和交换
size() 返回容器中元素的数目
empty() 判断容器是否为空
swap(st) 交换两个集合容器
注意: set容器不能重新指定容器大小
void test102()
{
set<int>s1;
//插入数据只有insert方式
s1.insert(10);
s1.insert(20);
s1.insert(30);
s1.insert(40);
//大小
cout << "大小" << s1.size() << endl;
//判断是否为空
if (empty(s1))
{
cout << "s1为空" << endl;
}
//交换
set<int>s2;
//插入数据只有insert方式
s2.insert(10);
s2.insert(20);
printSet(s2);
s2.swap(s1);
cout << "交换后" << endl;
printSet(s2);
}
查找和统计
find(key) 查找key是否存在,若存在,返回该键的元素的迭代器,不存在返回set.end()
count(key) 统计key的元素个数
//查找和统计
void test103()
{
set<int>s1;
//插入数据只有insert方式
s1.insert(10);
s1.insert(20);
s1.insert(30);
s1.insert(40);
//查找
set<int>::iterator it = s1.find(10);
cout << *it << endl;
if (s1.count(20))
{
cout << "存在该数据" << endl;
}
}
set和multiset的区别
set不可以插入重复数据,而multiset可以
set插入数据的同时会返回插入结果,表示插入是否成功
multiset不会检测数据,因此可以插入重复数据
//set和multiset的区别
void test104()
{
set<int>s;
pair<set<int>::iterator,bool> ret = s.insert(10);
if (ret.second)
{
cout << "第一次插入成功" << endl;
}
else
{
cout << "第一次插入失败" << endl;
}
ret = s.insert(10);
if (ret.second)
{
cout << "第二次插入成功" << endl;
}
else
{
cout << "第二次插入失败" << endl;
}
multiset<int>ms;
ms.insert(10);
ms.insert(10);
for (multiset<int>::iterator it = ms.begin(); it != ms.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
set容器的排序
set容器默认排序规则为从小到达,掌握如何改变排序规则
主要技术点:
利用仿函数,可以改变排序规则
示例代码
//仿函数
class MyCompare1
{
public:
bool operator() (int v1, int v2)const
{
return v1 > v2;
}
};
//set容器的排序
void test105()
{
set<int>s1;
//插入数据只有insert方式
s1.insert(10);
s1.insert(20);
s1.insert(60);
s1.insert(40);
printSet(s1);
//利用仿函数指定排序规则为从大到小
set<int, MyCompare1>s2;
//插入数据只有insert方式
s2.insert(10);
s2.insert(20);
s2.insert(60);
s2.insert(40);
for(set<int,MyCompare1>::iterator it2 = s2.begin(); it2 != s2.end(); it2++)
{
cout << *it2 << " ";
}
cout << endl;
}
补充知识点
pair对组创建
功能描述
成对出现的数据,利用对组可以返回两个数据
两种创建方式:
pair<type, type> p(valus1, value2);
pair<type, type> p = make_pair(value1, value2);
void test201()
{
//第一种方式
pair<string, int>p("Tom", 20);
cout << "姓名:" << p.first << "年龄:" << p.second << endl;
//第二种方式
pair<string, int>p2 = make_pair("Jerry", 30);
cout << "姓名:" << p2.first << "年龄:" << p2.second <<endl;
}