头文件:
#include <iostream>
#include <map>
#include <time.h>
#include <functional>
#include <vector>
#include <algorithm>
using namespace std;
(一)按照key值进行排序
1.1升序
void lessToKey()
{
srand((unsigned)time(NULL)); //产生一个随机数
map<int, int> ma; //map表的第三个参数默认为less<int>,所以默认是按照key升序
int len; cin >> len;
for (int i = 0; i < len; i++)
{
int a = rand() * rand() % 5;
int b = rand() * rand() % 8;
ma.insert(make_pair(a, b));
}
for (auto it = ma.begin(); it != ma.end(); it++)
{
cout << "key: " << it->first << " val: " << it->second << endl;
}
}
1.2降序
void greaterToKey()
{
srand((unsigned)time(NULL)); //产生一个随机数
map<int, int, greater<int> > ma; //如果想要按照key值降序排列,则在第三个参数显示的调用greater降序函数,剩下的操作和升序一样