排序矩阵到第n列C ++ [英] sort matrix up to nth column c++
问题描述
如果我有一个像这样的矩阵:
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
如何使用C ++ 14实现这一目标?
How can I achieve that using C++14?
推荐答案
在您期望的输出中,由于排序是行,因此标题不准确.
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} };
给出C样式的2D数组,对前2行进行排序:
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]));
输出:
3 4 5
6 7 8
9 5 4
2 1 3
如果您想使用C ++容器(例如建议使用的向量),或者对于固定大小的数组,请使用std::array
:
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
:
对整个2D向量进行排序的示例(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]));
如您所见,这是一种更友好的方法,即让C ++容器具有一个存储其自身大小的成员.
As you can see it's a more friendly approach give that C++ containers have a member which stores its own size.
输出:
3 4 5
6 7 8
4 5 9
1 2 3
这篇关于排序矩阵到第n列C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!