我正在尝试对向量对进行排序,但我无法理解此代码中的错误。
#include <bits/stdc++.h>
bool sortbysec(const pair<int,int> &a, const pair<int,int> &b) {
return (a.second < b.second);
}
using namespace std;
int main() {
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
long int t, i;
cin >> t;
vector<pair<int, int>> vect;
pair<int, int> tmp;
for (i = 0; i < t; i++) {
cin >> tmp.first;
vect.push_back(tmp);
}
sort(vect.begin(), vect.end(), sortbysec);
return 0;
}
有人请帮助我了解这段代码的错误。
首先,我想指出您的错误1.始终在头文件之后使用命名空间std进行写入,因为您正在自定义比较器下面进行写入,因此编译器无法解析什么对,因为它属于std命名空间。2.由于您要按第二个值对配对,因此您也应该在输入中取第二个值。
#include <bits/stdc++.h>
using namespace std;
bool sortbysec(const pair<int,int> &a, const pair<int,int> &b)
{
return (a.second < b.second);
}
int main(){
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
long int t, i;
cin >> t;
vector<pair<int, int> > vect;
pair<int, int> tmp;
for(i=0; i<t; i++){
cin>>tmp.first >> tmp.second;
vect.push_back(tmp);
}
cout << "Before Sorting" << "\n";
for (int i = 0; i < t; i ++) {
cout <<vect[i].first << " " << vect[i].second << "\n";
}
sort(vect.begin(), vect.end(), sortbysec);
cout << "after Sorting" << "\n";
for (int i = 0; i < t; i ++) {
cout <<vect[i].first << " " << vect[i].second << "\n";
}
return 0;
}
我已经重构了您的代码,希望对您有所帮助。输入项42 34 12 63 2输出量排序之前2 34 12 63 2排序后4 13 22 32 6
您仅按对.second
值进行排序,并且仅输入.first
值。要解决此问题,您可以:
1。更改排序功能以按.first
值对进行排序:
bool sortbyfirst(const pair<int,int> &a, const pair<int,int> &b) {
return (a.first < b.first);
}
2。输入要配对的.second
值:
for (i = 0; i < t; i++) {
cin >> tmp.first;
cin >> tmp.second; // Add this line
vect.push_back(tmp);
}
3。 {{Combine}}同时输入.first
和.second
,并按以下两项进行排序:
bool sort_by_first_and_sec(const pair<int,int> &a, const pair<int,int> &b) {
return a.first <= b.second && a.second < b.second;
}
我同意@ WhozCraig。您的自定义比较器仅比较每对中的.second
元素,而您从未设置为任何元素。
尝试输入.second
值。
看看下面的实现:
#include <iostream>
#include <utility>
#include <vector>
#include <algorithm>
bool sortbysec(const std::pair<int,int> &a, const std::pair<int,int> &b) {
return (a.second < b.second);
}
int main() {
int t, i;
std::cin >> t;
std::vector<std::pair<int, int>> vect;
std::pair<int, int> tmp;
for (i = 0; i < t; i++) {
std::cin >> tmp.first;
std::cin >> tmp.second;
vect.push_back(tmp);
}
sort(vect.begin(), vect.end(), sortbysec);
for (i = 0; i < t; i++) {
std::cout<<vect[i].first<<" "<<vect[i].second<<std::endl;
}
return 0;
}
输入:
5
1 5
2 4
3 3
4 2
5 1
输出:
5 1
4 2
3 3
2 4
1 5
更现代(更紧凑)的代码版本(C ++ 14):
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
int main() {
long int t;
std::cin >> t;
std::vector<std::pair<int, int>> v(t);
for (auto &i : v)
std::cin >> i.first >> i.second;
std::sort(v.begin(), v.end(), [](const auto &a, const auto &b) {
return a.second < b.second;
});
for (auto &i : v)
std::cout << i.first << ' ' << i.second << '\n';
return 0;
}