前提
今日,个人在尝试对二维向量进行排序时,发现自带的sort函数,只会默认以第一个元素作为排序对象,如果想以某一个对应位置的元素作为排序对象,则需要自定义一个比较函数。
实现代码
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;
class MySort
{
public:
MySort(int i) :index(i){};
bool operator()(vector<int>& v1, vector<int>& v2)
{
return v1[index] < v2[index];
}
private:
int index;
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<vector<int>> rr = { { 1, 3, 7 }, { 7, 1, 5 }, { 3, 2, 2 } };
sort(rr.begin(), rr.end(),MySort(1));
for (auto rrr : rr){
for (auto aa : rrr)
cout << aa << " ";
cout << endl;
}
system("pause");
return 0;
}