set
set集合容器实现了红黑树(Red-Black Tree)的平衡二叉检索树的的数据结构,在插入元素时,它会自动调整二叉树的排列,把该元素放到适当的位置,以确保每个子树根节点的键值大于左子树所有节点的键值,而小于右子树所有节点的键值;另外,还得确保根节点的左子树的高度与有字数的高度相等,这样,二叉树的高度最小,从而检索速度最快。要注意的是,它不会重复插入相同键值的元素,而采取忽略处理。
Set容器特点:相同的值不再存储,存进去后自动排序。
首先要引入头文件 #include <set> . 并使用命名空间 using namespace std;
1、创建set
set<int> s;
2、插入元素
采用inset()方法把元素插入到集合中,插入规则在默认的比较规则下,是按元素值从小到大插入,如果自己指定了比较规则函数,则按自定义比较规则函数插入。使用前向迭代器对集合中序遍历,结果正好是元素排序后的结果。
set<int> s; s.insert(5); //第一次插入5,可以插入 s.insert(1); s.insert(6); s.insert(3); s.insert(5); //第二次插入5,重复元素,不会插入
3、中序遍历set
使用前向迭代器对集合中序遍历,结果正好是元素排序后的结果。
#include<iostream>
#include<set>
using namespace std;
int main()
{
set<int> s;
s.insert(5); //第一次插入5,可以插入
s.insert(1);
s.insert(6);
s.insert(3);
s.insert(5); //第二次插入5,重复元素,不会插入
set<int>::iterator it; //定义前向迭代器
//中序遍历集合中的所有元素
for(it = s.begin(); it != s.end(); it++)
{
cout << *it << " ";
}
cout << endl;
return 0;
}
4、元素的反向遍历
set<int>::reverse_iterator rit; //定义反向迭代器
for (rit = s.rbegin(); rit != s.rend(); rit++)
{
cout << *rit << " ";
}
5、元素的删除
与插入元素的处理一样,集合具有高效的删除处理功能,并自动重新调整内部的红黑树的平衡。删除的对象可以是某个迭代器位置上的元素、等于某键值的元素、一个区间上的元素和清空集合。
s.erase(6); //删除键值为6的元素
6、元素的检索
使用find()方法对集合进行检索,如果找到查找的的键值,则返回该键值的迭代器位置;否则,返回集合最后一个元素后面的一个位置,即end()。
set<int>::iterator it;
it = s.find(6); //查找键值为6的元素
if (it != s.end())
{
cout << *it << endl;
}
7、自定义比较函数
a、集合中元素非结构体
#include<iostream>
#include<set>
using namespace std;
struct mycomp
{ //自定义比较函数,重载“()”操作符
bool operator() (const int &a, const int &b)
{
if(a != b)
return a > b;
else
return a > b;
}
};
int main()
{
set<int, mycomp> s; //采用比较函数mycomp
s.insert(5); //第一次插入5,可以插入
s.insert(1);
s.insert(6);
s.insert(3);
s.insert(5); //第二次插入5,重复元素,不会插入
set<int,mycomp>::iterator it;
for(it = s.begin(); it != s.end(); it++)
cout << *it << " ";
cout << endl;
return 0;
}
b、集合中元素是结构体,那么可以直接把比较函数写在结构体内
#include<iostream>
#include<set>
#include<string>
using namespace std;
struct Info
{
string name;
double score;
bool operator < (const Info &a) const // 重载“<”操作符,自定义排序规则
{
//按score由大到小排序。如果要由小到大排序,使用“>”即可。
return a.score < score;
}
};
int main()
{
set<Info> s;
Info info;
//插入三个元素
info.name = "Jack";
info.score = 80;
s.insert(info);
info.name = "Tom";
info.score = 99;
s.insert(info);
info.name = "Steaven";
info.score = 60;
s.insert(info);
set<Info>::iterator it;
for(it = s.begin(); it != s.end(); it++)
cout << (*it).name << " : " << (*it).score << endl;
return 0;
}
浙公网安备 33010602011771号