std::sort(myVector.begin(), myVector.end(), [](const std::vector< int >& a, const std::vector< int >& b){
//If you want to sort in ascending order, then substitute > with <
return a[1] > b[1];
});
请注意,您将需要 C++11 编译器来编译此代码。您应该让 lambda 函数接受 const 引用以避免昂贵的副本,正如 Blastfurnace 所建议的那样。
#include <iostream>
#include <vector>
#include <algorithm>
int main(){
std::vector< std::vector< int > > myVector({{3,4,3},{2,5,2},{1,6,1}});
std::sort(myVector.begin(), myVector.end(), [](const std::vector< int >& a, const std::vector< int >& b){ return a[1] > b[1]; } );
std::cout << "{";
for(auto i : myVector){
std::cout << "[";
for(auto j : i)
std::cout << j << ",";
std::cout << "],";
}
std::cout << "}" << std::endl;
return 0;
}
程序的输出:
{[1,6,1,],[2,5,2,],[3,4,3,],}