Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++对同一时间向量的第一和第二排序_C++_Sorting - Fatal编程技术网

C++对同一时间向量的第一和第二排序

C++对同一时间向量的第一和第二排序,c++,sorting,C++,Sorting,这是我用来对向量排序的代码。但它只能根据配对中的第二个进行排序 sort(pair_vec.begin(), pair_vec.end(), sortbysecdesc); 这是我使用的驱动程序功能。如果几秒钟的时间相同,如何编码以升序按第一个顺序对向量排序- bool sortbysecdesc(const pair<int,char> &a, const pair<int,char> &b) { return a.second >

这是我用来对向量排序的代码。但它只能根据配对中的第二个进行排序

sort(pair_vec.begin(), pair_vec.end(), sortbysecdesc);
这是我使用的驱动程序功能。如果几秒钟的时间相同,如何编码以升序按第一个顺序对向量排序-

bool sortbysecdesc(const pair<int,char> &a, const pair<int,char> &b) {
       return a.second > b.second;
}
您需要检查第二个值是否相等,如果相等,则返回比较第一个值的结果,否则返回比较第二个值的结果:

例如:

bool sortbysecdesc(const pair<int,char> &a, const pair<int,char> &b) {
    return (a.second == b.second) ? (a.first < b.first) : (a.second > b.second);
}
输出:

vector<pair<int, char>> pair_vec{ {1,'a'}, {2,'b'}, {3,'b'}, {4,'b'}, {5,'f'}, };
sort(pair_vec.begin(), pair_vec.end(), sortbysecdesc);
for (auto &p : pair_vec)
    cout << p.first << ' ' << p.second << endl;

将二进制函数更改为

bool sortbysecdesc(const pair<int,char> &a, const pair<int,char> &b) {
    return (a.second == b.second) ? (a.first < b.first) : (a.second > b.second);
}
vector<pair<int, char>> pair_vec{ {1,'a'}, {2,'b'}, {3,'b'}, {4,'b'}, {5,'f'}, };
sort(pair_vec.begin(), pair_vec.end(), sortbysecdesc);
for (auto &p : pair_vec)
    cout << p.first << ' ' << p.second << endl;
5 f 2 b 3 b 4 b 1 a
bool sortbysecdesc(const pair<int,char> &a, const pair<int,char> &b) {
    return (a.second == b.second) ? a.first < b.first : a.second > b.second;
}