步骤:
step1. 构建新的类型:typedef pair<int, int> PAIR;
step2. 对于step1构造的类型,新建一个vector:vector<PAIR> vec; // 重新定义类型
step3. 将unordered_map 中的值重新装入新定义的vector中:unordered_map<int,int> ans;
for(auto it=ans.begin();it!=ans.end();it++)
vec.push_back(make_pair(it->first, it->second));
step4. 重载排序规则:
int cmp(const PAIR& x, const PAIR& y)
{
return x.second > y.second; // 按照次数升序排序
}
step5.进行排序:
sort(vec.begin(), vec.end(), cmp); // vector根据cmp的规则进行排序
step6.完成,此时的vector就是一个unordered_map安装value排序的
参考:牛客网的题目(两个多项式的和)
代码如下:
#include<unordered_map>
#include<algorithm>
using namespace std;
// unordered_map 怎么安装key和value进行排序
// 定义新的类型:重新定义vector,然后对vector按照规则排序
typedef pair<int, int> PAIR;
// 重载排序函数
int cmp(const PAIR& x, const PAIR& y)
{
return x.first > y.first; // 按照次数升序排序
}
int main()
{
int m;
while(cin>>m)
{
unordered_map<int,int> ans;
while(m--)
{
int ci,xi;
cin>>xi>>ci;
ans[ci] += xi; // 将次数作为key,系数作为value,将系数进行加减
}
int n;
cin>>n;
while(n--)
{
int ci,xi;
cin>>xi>>ci;
ans[ci] += xi; // 将次数作为key,系数作为value,将系数进行加减
}
vector<PAIR> vec; // 重新定义类型
// 将unordered_map 中的值重新装入新定义的vector中
for(auto it=ans.begin();it!=ans.end();it++)
vec.push_back(make_pair(it->first, it->second));
sort(vec.begin(), vec.end(), cmp); // vector根据cmp的规则进行排序
for(int i=0;i<vec.size();i++)
if(vec[i].second!=0) // 系数为0的整数对不用输出
cout<<vec[i].second<<" "<<vec[i].first<<" ";
cout<<endl;
}
system("pause");
}