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
#include <algorithm>
#include <array>
#include <iostream>
#include <vector>
using namespace std;
#define N 3
void print(vector<array< int , N> > vect)
{
for (array< int , N> i : vect) {
for ( auto x : i)
cout << x << " " ;
cout << endl;
}
}
int main()
{
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);
sort(vect.begin(), vect.end());
cout << "Vector of arrays"
<< " after sorting: \n" ;
print(vect);
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
Share your thoughts in the comments
Please Login to comment...