一.主要用途:去重、排序
set中没有重复的元素,set中的元素都是排好序的。
set常用红黑树存储,插入、查找、删除时间复杂度均为O(logn)
二.常用方法
begin(); 第一个元素地址
clear(); 清楚set容器
count(x); x元素的个数
empty(); 是否为空
end(); 最后一个元素后面一个的地址
erase(x); 删除元素x
find(x); 查找元素x,返回地址,若没有则返回end
insert(x); 增加元素x
size(); 元素个数
三.申明
1.自定义比较函数 set<数据类型,比较函数>s;
#include<stdio.h>
#include<set>
#include<string>
using namespace std;
struct People
{
string name;
int age;/*
bool operator <(const People p) const //运算符重载
{
if(name==p.name)return false;//按名字去重
return age<p.age; //按照年龄由小到大进行排序
}*/
};
struct cmp {
bool operator ()(People a, People b)
{
if(a.name==b.name)return false;
return a.age<b.age; //按照年龄由小到大进行排序
}
};
int main()
{
set<People,cmp>s;
s.insert((People){"张三",14});
s.insert((People){"李四",16});
s.insert((People){"王二麻子",10});
s.insert((People){"张三",13});
set<People>::iterator it;
for(it=s.begin();it!=s.end();it++) //使用迭代器进行遍历
{
printf("姓名:%s 年龄:%d\n",(*it).name.c_str(),(*it).age);
}
return 0;
}
/*
输出结果
姓名:王二麻子 年龄:10
姓名:张三 年龄:14
姓名:李四 年龄:16
*/
2.友元函数重载< set<数据类型>s;
#include<stdio.h>
#include<set>
#include<string>
using namespace std;
struct People
{
string name;
int age;
bool operator <(const People p) const //运算符重载
{
if(name==p.name)return false;//按名字去重
return age<p.age; //按照年龄由小到大进行排序
}
};
int main()
{
set<People>s;
s.insert((People){"张三",14});
s.insert((People){"李四",16});
s.insert((People){"王二麻子",10});
s.insert((People){"张三",13});
set<People>::iterator it;
for(it=s.begin();it!=s.end();it++) //使用迭代器进行遍历
{
printf("姓名:%s 年龄:%d\n",(*it).name.c_str(),(*it).age);
}
return 0;
}
/*
输出结果
姓名:王二麻子 年龄:10
姓名:张三 年龄:14
姓名:李四 年龄:16
*/