user1893354 user1893354 - 1 month ago 8x
C++ Question

C++ sort 2d vector by column

Can someone tell me the best way to sort a 2d vector by column in C++ without using boost. I've done some searching and I can't find a good answer.



To answer this, I have to make assumptions, meaning you could have given us more information.

Assumption 1: What you call "2D vector" is a vector of vectors, e.g. a vector<vector<int>>.

Assumption 2a: the inner vectors are the rows, which means, you want to sort the outer vector by e.g. the second element of its inner vectors. In that case std::sort kicks in, which has an overload that takes a comparator as its third argument. The only thing you have to do is to write a comparator (i.e. a function or functor object), that takes two vectors and compares them by their N-th element. Should not be too hard.

Assumption 2b: the inner vectors are the columns, i.e. you want to sort one of the inner vectors and apply the reorderings to each other row as well. That's a bit more complicated, e.g. you could make another vector of indices 0 through N and sort that with a comparator that, given two indices i and j compares them by actually comparing column[i] and column[j]. After you have sorted that vector, you can accordingly reorder all the columns.