我们都用过sort()函数,对于一个vector vec;我们可以很轻松的写出:
//sort()函数默认使用升序排列
sort(vec.begin(),vec.end());
但是当我们碰到vector<vector>时,对于这样的二维数组我们想要按其某一列的元素的大小进行排列应该怎么解决呢?
这个时候就可以重写sort()
函数的第三个参数了,具体实现如下:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class comp
{
public:
bool operator()(vector<int> a, vector<int> b)
{
return a[1] < b[1];
}
};
int main()
{
vector<vector<int>> vec{
{
100,200},{
200,1300},{
1000,1250},{
2000,3200} };
sort(vec.begin(), vec.end(), comp());
for (const auto& p : vec)
{
cout << p[0] << "," << p[1] << endl;
}
}
还有一种在sort内定义的方法:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
vector<vector<int>> vec{
{
100,200},{
200,1300},{
1000,1250},{
2000,3200} };
sort(vec.begin(), vec.end(), [](const auto& a, const auto& b)
{
return a[1] < b[1];
});
for (const auto& p : vec)
{
cout << p[0] << "," << p[1] << endl;
}
}