# Sorting Vector of Arrays in C++

• Difficulty Level : Medium
• Last Updated : 01 Aug, 2020

Given a vector of arrays, the task is to sort them.

Examples:

Input: [[1, 2, 3], [10, 20, 30], [30, 60, 90], [10, 20, 10]]
Output: [[1, 2, 3], [10, 20, 10], [10, 20, 30], [30, 60, 90]]

Input: [[7, 2, 9], [5, 20, 11], [6, 16, 19]]
Output: [[5, 20, 11], [6, 16, 19], [7, 2, 9]]

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach:

To sort the Vector of Arrays using the built-in sort() in C++ STL it needs an array template which defined in a boost libraries, to store vector of arrays.

std:: vector<std:: array >

where, std::array is a container that encapsulates fixed size arrays.

In this problem, sort() function takes two arguments first(begin position of the vector) and second(end position of the vector) to sorts a vector of arrays (items with random access). Below is a simple program to show the working of sort().

## CPP

 `// C++ program to sort the vector``// of array by sort() function``// using STL in c++`` ` `#include ``#include ``#include ``#include ``using` `namespace` `std;`` ` `#define N 3`` ` `// Function to print vector of arrays``void` `print(vector > vect)``{`` ` `    ``// Displaying the vector of arrays``    ``// ranged for loop is supported``    ``for` `(array<``int``, N> i : vect) {``        ``for` `(``auto` `x : i)``            ``cout << x << ``" "``;``        ``cout << endl;``    ``}``}`` ` `// Driver code``int` `main()``{``    ``// std::array is a container that``    ``// encapsulates fixed size arrays.``    ``vector > vect;``    ``vect.push_back({ 1, 2, 3 });``    ``vect.push_back({ 10, 20, 30 });``    ``vect.push_back({ 30, 60, 90 });``    ``vect.push_back({ 10, 20, 10 });`` ` `    ``cout << ``"Vector of arrays"``         ``<< ``" before sorting: \n"``;``    ``print(vect);`` ` `    ``// Sorting the vector using built-in sort()``    ``// defined in algorithm header in C++ STL``    ``sort(vect.begin(), vect.end());`` ` `    ``cout << ``"Vector of arrays"``         ``<< ``" after sorting: \n"``;``    ``print(vect);`` ` `    ``// End of program``    ``return` `0;``}`

Output:

```Vector of arrays before sorting:
1 2 3
10 20 30
30 60 90
10 20 10

Vector of arrays after sorting:
1 2 3
10 20 10
10 20 30
30 60 90
```

My Personal Notes arrow_drop_up