平衡二叉检索树使用中序遍历算法,检索效率高于vector、deque和list等容器,另外使用中序遍历可将键值按照从小到大遍历出来。
构造set集合主要目的是为了快速检索,不可直接去修改键值。
常用操作:
1.元素插入:insert()
2.中序遍历:类似vector遍历(用迭代器)
3.反向遍历:利用反向迭代器reverse_iterator。
例:
set<int> s;
......
set<int>::reverse_iterator rit;
for(rit=s.rbegin();rit!=s.rend();rit++)
4.元素删除:与插入一样,可以高效的删除,并自动调整使红黑树平衡。
set<int> s;
s.erase(2); //删除键值为2的元素
s.clear();
5.元素检索:find(),若找到,返回该键值迭代器的位置,否则,返回最后一个元素后面一个位置。
set<int> s;
set<int>::iterator it;
it=s.find(5); //查找键值为5的元素
if(it!=s.end()) //找到
cout<<*it<<endl;
else //未找到
cout<<"未找到";
6.set的含义是集合,它是一个有序的容器,里面的元素都是排序好的,支持插入,删除,查找等操作,就
7.自定义类,需要重载运算符才能使用set
#include<iostream>
#include<set>
using namespace std;
typedef struct {
int a,b;
char s;
}newtype;
struct compare
{
bool operator()(const newtype &a, const newtype &b) const
{
return a.s<b.s;
}
};//the “; ”
set<newtype,compare>element;
int main()
{
newtype a,b,c,d,t;
a.a=1; a.s='b';
b.a=2; b.s='c';
c.a=4; c.s='d';
d.a=3; d.s='a';
element.insert(a);
element.insert(b);
element.insert(c);
element.insert(d);
set<newtype,compare>::iterator it;
for(it=element.begin(); it!=element.end();it++)
cout<<(*it).a<<" ";
cout<<endl;
for(it=element.begin(); it!=element.end();it++)
cout<<(*it).s<<" ";
}
element自动排序是按照char s的大小排序的;
8.set的基本操作:
begin()
clear()
count()
empty()
end()
equal_range()
erase()
find()
get_allocator() 返回集合的分配器
insert()
lower_bound()
key_comp()
max_size()
rbegin()
rend()
size()
swap()
upper_bound()
value_comp()