问题描述
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<string.h>
#include<map>
#include<functional>
using namespace std;
map<string,int> m;
vector<pair<pair<string,int>,int>> v;
vector<pair<pair<string,int>> v3;
vector<pair<pair<string,int>> v2[1001];
int N;
int idx;
bool cmp(const pair<pair<string,int>& n1,pair<pair<string,int>& n2)
{
return n1.first.first < n2.first.first;
}
bool cmp2(const pair<pair<string,int>& n2)
{
if(n1.first.first==n2.first.first)
return n1.first.second > n2.first.second;
}
bool cmp3(const pair<pair<string,int>& n2)
{
if(n1.first.first==n2.first.first)
if (n1.first.second == n2.first.second)
return n1.second > n2.second;
}
int main(void)
{
int N;
string s;
int num;
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> s >> num;
m[s]+= num;
v.push_back(make_pair(make_pair(s,num),i));
}
sort(v.begin(),v.end(),cmp);
sort(v.begin(),cmp2);
sort(v.begin(),cmp3);
//for (auto it = v.begin(); it != v.end(); it++)
//{
// cout << "first: " << it->first.first << " second: " << it->first.second << " " << it->second << endl;
//}
for (int i = 0; i < v.size(); i++)
{
v3.push_back(v[i]);
}
for (auto it = v3.begin(); it != v3.end(); it++)
{
cout << "first: " << it->first.first << " second: " << it->first.second << " third: " << it->second << endl;
}
}
我有一个排序问题,不知道y cmp3一直出错... 尝试对第三个元素降序排序(而第二个元素相同) 我该如何解决?
输入数据为
8
经典1000
经典500
流行音乐300
经典1000
经典600
流行100
经典1000
经典1000
解决方法
比较函数cmp2
和cmp3
具有未定义的行为-它们不会为每个输入返回值。因此,他们不会真正对向量进行排序。
我怀疑您可能试图将所有三个比较功能一起使用,但是实际上它们在3次不同的时间将其完全重新排序。您需要将整个行为放在一个排序函数中:
bool cmp3(const pair<pair<string,int>,int>& n1,pair<pair<string,int>& n2)
{
if (n1.first.first != n2.first.first) {
return n1.first.first < n2.first.first;
}
if (n1.first.second != n2.first.second) {
return n1.first.second < n2.first.second;
}
return n2.second < n1.second; // descending
}