Reputation: 805
If I have a matrix like this:
4 5 3
6 8 7
9 5 4
2 1 3
and I want only to sort only the first two rows such that I get:
3 4 5
6 7 8
9 5 4
2 1 3
How can I achieve that using C++14?
Upvotes: 0
Views: 739
Reputation: 23792
In your expected output, what you sort are the rows, so your title is not accurate.
Taking the sample output you present:
int mat[][3] = { {4, 5, 3},
{6, 8, 7},
{9, 5, 4},
{2, 1, 3} };
Given the C-style 2D array, to sort the first 2 rows:
#include <algorithm>
//...
std::sort(std::begin(mat[0]), std::end(mat[0]));
std::sort(std::begin(mat[1]), std::end(mat[1]));
To sort the whole array, you would use a cycle:
for(size_t i = 0; i < sizeof(mat) / sizeof(mat[0]); i++) //deduce the number of rows
std::sort(std::begin(mat[i]), std::end(mat[i]));
Output:
3 4 5
6 7 8
9 5 4
2 1 3
If you want to use a C++ container like, let's say, a vector of vectors, as it would be recommended, or for a fixed size array a std::array
:
Sample to sort the whole 2D vector (The same method for std::array
)
std::vector<std::vector<int>> mat = {
{4, 5, 3},
{6, 8, 7},
{9, 5, 4},
{2, 1, 3}};
for(size_t i = 0; i < mat.size(); i++)
std::sort(std::begin(mat[i]), std::end(mat[i]));
As you can see it's a more friendly approach give that C++ containers have a member which stores its own size.
Output:
3 4 5
6 7 8
4 5 9
1 2 3
Upvotes: 2
Reputation: 475
C++ STL provides a function sort that sorts a vector or array. The average of a sort complexity is N*log2 (N)
Syntax:
sort(first, last);
Here, first – is the index (pointer) of the first element in the range to be sorted. last – is the index (pointer) of the last element in the range to be sorted.
Example:
For sorting the first row of the matrix:
sort(m[0].begin(),m[0].end());
you can use a loop to sort some n rows like this:
for(int i=0;i<n;i++)
{
sort(m[i].begin(),m[i].end());
}
by default sort() function sort the array in ascending order. If you want to sort in descending order then for a vector v ,you can do it like this:
sort(v.begin(),v.end(),greater<int>());
if you are using an array (assume arr where the size of arr is n)then you can use the sort function like this:
sort(arr,arr+n)
Upvotes: 1