Skip to content
Related Articles

Related Articles

Sorting Vector of Arrays in C++
  • 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]]

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 <algorithm>
#include <array>
#include <iostream>
#include <vector>
using namespace std;
  
#define N 3
  
// Function to print vector of arrays
void print(vector<array<int, N> > 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<array<int, N> > 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
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :