大家都知道,Set容器有其特定的排序准则,缺省情况下以operator<进行比较,也就是默认升序排列,
那么怎么改变容器的排序准则呢,那就是在容器定义的时候, 把准则作为第二个template参数传入。
如果想定义成按递减顺序排列,定义成typedef set<int,greater<int> > IntSet; greater<>是一个预先定义的仿函数。
下面是代码实现:
#include "stdafx.h"
#include <set>
using namespace std;
typedef set<int,greater<int> > IntSet;
int _tmain(int argc, _TCHAR* argv[])
{
IntSet coll;
coll.insert(3);
coll.insert(1);
coll.insert(5);
coll.insert(4);
coll.insert(6);
coll.insert(2);
IntSet::const_iterator it = coll.begin();
for( ;it != coll.end();++it)
{
printf("元素值%d\n", *it);
}
return 0;
}
参考《C++标准程序库》