# Sorting 2D Vector in C++ | Set 3 (By number of columns)

We have discussed some of the cases of sorting 2D vector in below set 1 and set 2.

As mentioned in one of the article publised of this set, A 2D Vector can also have rows with different number of columns. This property is unlike the 2D Array in which all rows have same number of columns.

 // C++ code to demonstrate 2D Vector // with different no. of columns #include #include // for 2D vector using namespace std; int main() {     // Initializing 2D vector "vect" with     // values     vector< vector > vect{{1, 2},                                {3, 4, 5},                                {6}};        // Displaying the 2D vector     for (int i=0; i

Output:

1 2
3 4 5
6

Case 5 : Sorting the 2D Vector on basis of no. of columns in row in ascending order.

In this type of sorting, 2D vector is sorted on basis of a no. of column in ascending order. This is achieved by passing a third argument in “sort()” as a call to user defined explicit function.

 // C++ code to demonstrate sorting of // 2D vector on basis of no. of columns // in ascending order #include #include // for 2D vector #include // for sort() using namespace std;    // Driver function to sort the 2D vector // on basis of a no. of columns in  // ascending order bool sizecom(const vector& v1, const vector& v2) {     return v1.size() < v2.size(); }    int main() {     // Initializing 2D vector "vect" with     // values     vector< vector > vect{{1, 2},                                {3, 4, 5},                                {6}};        // Displaying the 2D vector before sorting     cout << "The Matrix before sorting is: ";     for (int i=0; i

Output:

The Matrix before sorting is:
1 2
3 4 5
6
The Matrix after sorting is:
6
1 2
3 4 5

Case 6 : Sorting the 2D Vector on basis of no. of columns in row in descending order.

In this type of sorting, 2D vector is sorted on basis of a no. of column in descending order. This is achieved by passing a third argument in “sort()” as a call to user defined explicit function.

 // C++ code to demonstrate sorting of // 2D vector on basis of no. of columns // in descending order #include #include // for 2D vector #include // for sort() using namespace std;    // Driver function to sort the 2D vector // on basis of a no. of columns in  // descending order bool sizecom(const vector& v1, const vector& v2) {     return v1.size() > v2.size(); }    int main() {     // Initializing 2D vector "vect" with     // values     vector< vector > vect{{1, 2},                       {3, 4, 5},                   {6}};        // Displaying the 2D vector before sorting     cout << "The Matrix before sorting is: ";     for (int i=0; i

Output:

The Matrix before sorting is:
1 2
3 4 5
6
The Matrix after sorting is:
3 4 5
1 2
6