sort 3d vector based on one row (c++, std::sort)

268 Views Asked by At

i want to sort a 3d vector, e.g.

3 2 1 4 5
1 2 3 4 5
5 4 3 2 1

by one row. The result when to be sorted based on the first row should be:

1 2 3 4 5
3 2 1 4 5
3 4 5 2 1

I think that is very easy by using the right compare function in std::sort, but how?

Thanks!

2

There are 2 best solutions below

3
On

First of all

3 2 1 4 5
1 2 3 4 5
5 4 3 2 1

doesn't make up a 3d, but a 2d vector that should be defined like this

std::vector<std::vector<int>> myvect = 
     { { 3, 2, 1, 4, 5 } 
     , { 1, 2, 3, 4, 5 }
     , { 5, 4, 3, 2, 1 }
     };

There's no intrinsic compare function provided for arbitrary std::vector<>'s, you have to implement one, and pass it to the std::sort() function.

0
On
std::vector<std::vector<int>> myvect = 
     { { 3, 2, 1 } 
     , { 1, 2, 3 }
     , { 5, 4, 3 }
     , { 0, 1, 3 }
     , { 7, 2, 5 }
     };

std::sort(myvect.begin(), myvect.end(), [](const std::vector<int> &a, const std::vector<int> &b) {
        return a.front()<b.front(); 
    });