std::sort(myVector.begin(), myVector.end(), [](const std::vector< int >& a, const std::vector< int >& b){
return a[1] > b[1];
});
Note that to compile this code, you will need a C ++ 11 compiler. You must have the lambda function accept constant links in order to avoid expensive copies, as Blastfurnace suggests.
#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;
}
Program Output:
{[1,6,1,],[2,5,2,],[3,4,3,],}
source
share