#include<iostream> #include<set> using namespace std; typedef struct { int i,j; char s; }Type; struct compare { bool operator()(const Type &a, const Type &b) const { return a.s<b.s;} }; set<Type,compare> setA; int main() { Type a,b,c,d,t; a.i=1; a.s=‘b‘; b.i=2; b.s=‘c‘; c.i=4; c.s=‘d‘; d.i=3; d.s=‘a‘; setA.insert(a); setA.insert(b); setA.insert(c); setA.insert(d); set<Type,compare>::iterator it; for(it=setA.begin(); it!=setA.end();it++) cout<<(*it).a<<" "; cout<<endl; for(it=setA.begin(); it!=setA.end();it++) cout<<(*it).s<<" "; }
Output:
1 :3 1 2 4
2 :a b c d
构造set集合主要目的是为了快速检索,不可直接去修改键值。
set 容器模版需要3个泛型参数,如下:
template<class T, class C, class A> class set;
第一个T 是元素类型,必选;
第二个C 指定元素比较方式,缺省为 Less<T>, 即使用 < 符号比较;
第三个A 指定空间分配对象,一般使用默认类型。
因此:
(1) 如果第2个泛型参数你使用默认值的话,你的自定义元素类型需要重载 < 运算操作;
(2)如果你第2个泛型参数不使用默认值的话,则比较对象必须具有 () 操作,即:
bool operator()(const T &a, const T &b)
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.自定义比较函数
(1)元素不是结构体:
例:
//自定义比较函数myComp,重载“()”操作符
struct myComp
{
bool operator()(const your_type &a,const your_type
&b)
[
return a.data-b.data>0;
}
}
set<int,myComp>s;
......
set<int,myComp>::iterator it;
(2)如果元素是结构体,可以直接将比较函数写在结构体内。
例:
struct Info
{
string name;
float score;
//重载“<”操作符,自定义排序规则
bool operator < (const Info &a)
const
{
//按score从大到小排列
return
a.score<score;
}
}
set<Info>
s;
......
set<Info>::iterator it;
#include <iostream> #include <set> using namespace std; bool fncomp (int lhs, int rhs) {return lhs<rhs;} struct classcomp { bool operator() (const int& lhs, const int& rhs) const {return lhs<rhs;} }; int main () { set<int> first; // empty set of ints int myints[]= {10,20,30,40,50}; set<int> second (myints,myints+5); // pointers used as iterators set<int> third (second); // a copy of second set<int> fourth (second.begin(), second.end()); // iterator ctor. set<int,classcomp> fifth; // class as Compare bool(*fn_pt)(int,int) = fncomp; set<int,bool(*)(int,int)> sixth (fn_pt); // function pointer as Compare return 0; }
原文:http://www.cnblogs.com/ct6816678/p/3689284.html