[英]How should I solve this c++ sorting problem
#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>,int>> v3;
vector<pair<pair<string, int>, int>> v2[1001];
int N;
int idx;
bool cmp(const pair<pair<string, int>,int>& n1, pair<pair<string, int>, int>& n2)
{
return n1.first.first < n2.first.first;
}
bool cmp2(const pair<pair<string, int>, int>& n1, pair<pair<string, int>, int>& n2)
{
if(n1.first.first==n2.first.first)
return n1.first.second > n2.first.second;
}
bool cmp3(const pair<pair<string, int>, int>& n1, pair<pair<string, int>, 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(), v.end(), cmp2);
sort(v.begin(), v.end(), 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 次不同的时间完全重新排序。 您需要将整个行为放在一个排序中 function:
bool cmp3(const pair<pair<string, int>, int>& n1, pair<pair<string, int>, 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.