Tur*_*101 2 c++ sorting stdvector
假设我有这个向量向量[[5,10],[2,5],[4,7],[3,9]],我想使用sort()cpp的方法对它进行排序,这样[[5,10],[3,9],[4,7],[2,5]]排序后就变成这样了。那就是我想根据第二个索引进行排序。
现在我已经编写了这段代码来对向量的向量进行排序,但它无法正常工作。
static bool compareInterval( vector<vector<int>> &v1, vector<vector<int>> &v2)
{
return (v1[0][1]>v2[0][1]);
}
sort(boxTypes.begin(), boxTypes.end(), compareInterval);
Run Code Online (Sandbox Code Playgroud)
谁能告诉我哪里出了问题,我该如何纠正。提前致谢。
你的排序可能看起来像
std::sort(boxTypes.begin(), boxTypes.end(), [](auto const& lhs, auto const& rhs) {
return lhs[1] > rhs[1];
});
Run Code Online (Sandbox Code Playgroud)
换句话说,按[1]每个向量的元素排序并使用>按降序排序。请注意,在 lambda 函数中lhs和rhs的类型为const std::vector<int>&。
小智 5
当您的代码对向量的向量进行排序时,它会传递两个向量(不是向量的向量)到布尔函数,并对它们进行比较以确定它们是否需要互换,或者它们相对于彼此的位置是否正确。
因此,这里您只需要比较 2 个向量(您已尝试比较向量的向量)。
您需要进行的更改compareInterval是:
static bool compareInterval( vector<int> &v1, vector<int> &v2)
{
return (v1[1]>v2[1]);
}
Run Code Online (Sandbox Code Playgroud)
在下面找到我的测试代码:
#include <bits/stdc++.h>
using namespace std;
static bool compareInterval( vector<int> &v1, vector<int> &v2)
{
return (v1[1]>v2[1]);
}
int main() {
vector<vector<int>> boxTypes = {{5,10},{2,5},{4,7},{3,9}};
sort(boxTypes.begin(), boxTypes.end(), compareInterval);
for(int i=0;i<4;i++)
cout<<boxTypes[i][0]<<" "<<boxTypes[i][1]<<"\n";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1990 次 |
| 最近记录: |