平时在用到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从大到小排序。