c++ stl set之顺序排序。

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

首先看看标准map的定义:

template < class T,                        // set::key_type/value_type
           class Compare = less<T>,        // set::key_compare/value_compare
           class Alloc = allocator<T>      // 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 <iostream>
#include <set>
using namespace std;
set <int, greater<int> > setTest;
int main()
{
    setTest.insert(343);
    setTest.insert(2);
    setTest.insert(3344);
    setTest.insert(1);
    setTest.insert(90);
    for(set<int,greater<int> >::iterator i = setTest.begin(); i !=setTest.end();i++)
        cout << *i << endl;
     for(set<int,greater<int> >::reverse_iterator i = setTest.rbegin(); i !=setTest.rend();i++)
        cout << *i << endl;
    cout << "Hello world!" << endl;
    int x;
    cin >> x;
    return 0;
}
程序的输出结果是:


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

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值