c++ stl set之顺序排序。

平时在用到map容器的时候,想到的只是他是存储键值对的,类似哈希表,但最近看剑指offer上的一道题目——寻找最小的K个数,才知道map还可以在定义的时候就定义了其排列顺序。

首先看看标准map的定义:

template < class T,                        // set::key_type/value_type
           class Compare = less,        // set::key_compare/value_compare
           class Alloc = allocator      // set::allocator_type
           > class set;

Sets are containers that store unique elements following a specific order.

In a set, the value of an element also identifies it (the value is itself the key, of type T), and each value must be unique. 

The value of the elements in a set cannot be modified once in the container (the elements are always const), 

but they can be inserted or removed from the container.Internally, 

the elements in a set are always sorted following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).

从上面的介绍,我们就可以知道,map定义的时候可以定义指定的排序方式,并且其排序方式是按照键的大小进行的。

下面为我写的一个小程序测试的map顺序。

#include 
#include 
using namespace std;
set  > setTest;
int main()
{
    setTest.insert(343);
    setTest.insert(2);
    setTest.insert(3344);
    setTest.insert(1);
    setTest.insert(90);
    for(set >::iterator i = setTest.begin(); i !=setTest.end();i++)
        cout << *i << endl;
     for(set >::reverse_iterator i = setTest.rbegin(); i !=setTest.rend();i++)
        cout << *i << endl;
    cout << "Hello world!" << endl;
    int x;
    cin >> x;
    return 0;
}
程序的输出结果是:


定义set的时候,用的一个greater作为第二个参数,即使set中的元素按照键的大小从大到小排序,若要实现从小打到排序,则使用reverse_iterator即可。

map类同,定义的时候map >即可实现按照key从大到小排序。

你可能感兴趣的:(c++ stl set之顺序排序。)