Set 总结
SET 是有序的存储不同元素的容器。内部实现为红黑树。
定义set
#include <set>
#include <iostream>
using namespace std;
struct node {
int num;
string s;
bool operator < (const node a) const {
return num<a.num;
}
};
int main()
{
set<int> s1;
set<string> s2;
set<node> s3;
return 0;
}
1.元素为数字时,默认从小到大排序
2.元素是string 按照字典序排序
3.元素是struct,要重载<运算符,或者写一个比较函数,value_comp函数进行排序
基本属性
方法 | 含义 |
---|---|
begin(); | 元素的第一个位置 |
end(); | 末尾元素位置的下一个位置 |
rbegin(); | 反向迭代的第一个位置 |
rend(); | 反向迭代的最后一个位置的下一个位置 |
empty(); | 是否为空 |
size(); | 元素数量 |
maxsize(); | 最大容纳的数量 |
#include <set>
#include <iostream>
using namespace std;
int main()
{
set<int> s1;
for ( int i=10; i>0; i-- )
s1.insert(i);
set<int>::iterator it;
cout<<"Size "<<s1.size()<<endl;
for ( it = s1.begin(); it!=s1.end(); it++ )
cout<<*it<<" ";
cout<<endl;
set<int>::reverse_iterator it2;
for ( it2 = s1.rbegin(); it2!=s1.rend(); it2++ )
cout<<*it2<<" ";
cout<<endl;
return 0;
}
集合操作
方法 | 含义 |
---|---|
insert(tyep data); | 插入data |
erase(value); | 删除value |
erase(firse,end); | 删除从first到end的元素,不包含end指向元素 |
erase(iterator it); | 删除it指向的元素 |
clear(); | 全部清空 |
find(value); | 返回value的位置 |
count(value); | 出现次数 |
#include <set>
#include <iostream>
using namespace std;
struct node {
int num;
string s;
bool operator < (const node a) const {
return num<a.num;
}
};
int main()
{
set<int> s1;
for ( int i=10; i>0; i-- )
s1.insert(i);
s1.erase(1);
set<int>::iterator it;
set<int>::iterator it1;
set<int>::iterator it2;
it1 = s1.find(2);
it2 = s1.find(5);
s1.erase(it1,it2);
cout<<"size "<<s1.size()<<endl;
cout<<"count 10 "<<s1.count(10)<<endl ;
for ( it = s1.begin(); it!=s1.end(); it++ )
cout<<*it<<" ";
cout<<endl;
return 0;
}