sort matrix up to nth column c++

淺唱寂寞╮ 提交于 2020-06-17 09:36:10

问题


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?


回答1:


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)



回答2:


In your expected output, what you sort are the rows, so your title is not accurate.

Taking the sample output you present:

Live demo

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 


来源:https://stackoverflow.com/questions/61999188/sort-matrix-up-to-nth-column-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!