利用一组数据来说明,sort函数进行二维vector的排序: envelopes = [[5,4],[6,4],[6,7],[2,3]] 代码如下:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
vector<vector<int>> envelopes(4,vector<int>(2,0));
int n;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
cin >> n;
envelopes[i][j] = n;
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
cout << envelopes[i][j] << " ";
}
cout << endl;
}
cout << endl;
sort(envelopes.begin(), envelopes.end(), [](const auto& e1, const auto& e2) {
return e1[0] < e2[0] || (e1[0] == e2[0] && e1[1] > e2[1]);
});
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
cout << envelopes[i][j] << " ";
}
cout << endl;
}
return 0;
}
运行结果如下:
|