// C++ code to demonstrate sorting of a
// 2D vector on basis of a column
#include <algorithm> // for sort()
#include <iostream>
#include <vector> // for 2D vector
using namespace std;
// Driver function to sort the 2D vector
// on basis of a particular column
bool sortcol(const vector<int>& v1, const vector<int>& v2)
{
return v1[1] < v2[1];
}
// Driver Code
int main()
{
// Initializing 2D vector "vect" with
// values
vector<vector<int> > vect{ { 3, 5, 1 },
{ 4, 8, 6 },
{ 7, 2, 9 } };
// Number of rows;
int m = vect.size();
// Number of columns (Assuming all rows
// are of same size). We can have different
// sizes though (like Java).
int n = vect[0].size();
// Displaying the 2D vector before sorting
cout << "The Matrix before sorting is:
";
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
cout << vect[i][j] << " ";
cout << endl;
}
// Use of "sort()" for sorting on basis
// of 2nd column
sort(vect.begin(), vect.end(), sortcol);
// Displaying the 2D vector after sorting
cout << "The Matrix after sorting is:
";
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
cout << vect[i][j] << " ";
cout << endl;
}
return 0;
}
9
The built-in arrays of C and C++ are very inflexible, among other things they cannot be assigned.
Your best option would be the 'array' class from the C++ standard library, at least for the inner dimension:
array<int, 2> a[5] = { { 20, 11 },
{ 10, 20 },
{ 39, 14 },
{ 29, 15 },
{ 22, 23 } };
sort( a, a + 5 );
Edit: Some more explanations.
Here we use the property of std::array that '<' by default compares them lexicographically, i.e. starts with the first element. In order to sort things differently we have to come up with an comparator object, so if you want to use the second column as sort key you have to do this:
auto comp = []( const array<int, 2>& u, const array<int, 2>& v )
{ return u[1] < v[1]; };
sort( a, a + 5, comp );
And as mentioned in the first comment, sort(a, a+5 ... is just an ugly short form for the cleaner sort(std::begin(a), std::end(a) ...
// C++ code to demonstrate sorting of a
// row of 2D vector
#include <algorithm> // for sort()
#include <iostream>
#include <vector> // for 2D vector
using namespace std;
// Driver Code
int main()
{
// Initializing 2D vector "vect" with
// values
vector<vector<int> > vect{ { 3, 5, 1 },
{ 4, 8, 6 },
{ 7, 2, 9 } };
// Number of rows;
int m = vect.size();
// Number of columns (Assuming all rows
// are of same size). We can have different
// sizes though (like Java).
int n = vect[0].size();
// Displaying the 2D vector before sorting
cout << "The Matrix before sorting 1st row is:
";
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
cout << vect[i][j] << " ";
cout << endl;
}
// Use of "sort()" for sorting first row
sort(vect[1].begin(), vect[1].end());
// Displaying the 2D vector after sorting
cout << "The Matrix after sorting 1st row is:
";
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
cout << vect[i][j] << " ";
cout << endl;
}
return 0;
}