简体   繁体   中英

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.

Thanks

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, eg a vector<vector<int>> .

Assumption 2a: the inner vectors are the rows, which means, you want to sort the outer vector by eg 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 (ie a function, function object, lambda etc.), 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 , ie 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, eg 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.

The sort() Function in STL can do it for you. You just need to write a function to compare 2 cases in your vector.

http://www.cplusplus.com/reference/algorithm/sort/

After, it depends the type of sort you need, you can sort the columns one by one, then the first row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM