VOOZH about

URL: https://www.geeksforgeeks.org/cpp/sorting-2d-vector-in-c-set-1-by-row-and-column/

⇱ Sorting 2D Vector in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sorting 2D Vector in C++

Last Updated : 19 Nov, 2024

Sorting is the process of arranging the elements of container in ascending order, descending order or in any user defined order. In this article, we will learn different ways in which a 2D vector can be sorted in C++.

By Rows

A 2D vector can be sorted by sorting each row in any desired order using sort() function on each individual row.


Output
3 3 5 
1 2 3 
4 7 8 

By Columns

A 2D vector can be sorted by sorting each column one by one in any desired order but sort() cannot be directly applied in this case instead, first transpose the 2D vector, sort each row (which represents the original columns) using the desired order and then transpose the 2D vector back to its original orientation.


Output
1 3 2 
3 4 3 
7 5 8 

By Rows and Columns

This method combines the above two methods of sorting by rows and sorting by columns by first, sorting the 2D vector row-wise, and then column-wise to desired order.


Output
1 2 3 
3 3 5 
4 7 8 

All Elements as a Whole

In this method of sorting, the whole vector is first flattened and then sorted so that all the elements of 2D vector should be in desired order from top to bottom zig-zag manner.


Output
1 2 3 
3 3 4 
5 7 8 
Comment
Article Tags: