【问题标题】:sort matrix up to nth column c++将矩阵排序到第n列c ++
【发布时间】:2020-05-25 20:22:53
【问题描述】:

如果我有这样的矩阵:

 4 5 3
 6 8 7
 9 5 4
 2 1 3

我只想对前两行进行排序,以便得到:

 3 4 5
 6 7 8
 9 5 4
 2 1 3

如何使用 C++14 实现这一点?

【问题讨论】:

  • 请附上minimal reproducible example。你使用什么数据结构?你可以使用std::sort
  • 你的意思是行,而不是列。
  • 不清楚是要单独对行进行排序,还是对前2行的内容进行排序并重新排列成2行。

标签: c++ sorting matrix


【解决方案1】:

在您的预期输出中,您排序的是行,因此您的标题不准确。

获取您提供的示例输出:

Live demo

int mat[][3] = { {4, 5, 3},
                 {6, 8, 7},
                 {9, 5, 4},
                 {2, 1, 3} }; 

给定 C 样式的 2D 数组,对前 2 行进行排序:

#include <algorithm>
//...                
std::sort(std::begin(mat[0]), std::end(mat[0]));
std::sort(std::begin(mat[1]), std::end(mat[1]));

要对整个数组进行排序,您可以使用循环:

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

Sample to sort the whole 2D vectorstd::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++ 容器有一个成员来存储自己的大小。

输出:

3 4 5 
6 7 8 
4 5 9 
1 2 3 

【讨论】:

  • 如果我使用向量,并且我想对所有列进行排序,我会这样做:sort(vect[0].begin(), vect[n-1].end()); ?因此,如果我想得到:3 4 5 6 7 8 4 5 9 1 2 3 将它们读取为矩阵
  • 你的意思是像std::vector&lt;std::vector&lt;int&gt;&gt;这样的向量?
  • std::sort(std::begin(mat[0]), std::end(mat[1])); 是迂腐的 UB,因为指针不属于同一个数组。
  • @Jarod42,C 风格的数组使用迭代器吗?
  • @Jarod42,那么它是否有效?鉴于 2D C 风格的数组是按行存储的?
【解决方案2】:

C++ STL 提供了对向量或数组进行排序的函数 sort。 一个排序复杂度的平均值是N*log2(N)

语法:

sort(first, last);

这里, first – 是要排序的范围内第一个元素的索引(指针)。 last – 是要排序的范围内最后一个元素的索引(指针)。

例子:

对矩阵的第一行进行排序:

sort(m[0].begin(),m[0].end());

您可以使用循环对一些 n 行进行排序,如下所示:

    for(int i=0;i<n;i++)
    {
     sort(m[i].begin(),m[i].end());
    }

默认情况下 sort() 函数按升序对数组进行排序。如果你想按降序排序,那么对于向量 v ,你可以这样做:

sort(v.begin(),v.end(),greater<int>());

如果您使用的是数组(假设 arr 的大小为 n),那么您可以像这样使用排序函数:

sort(arr,arr+n)

【讨论】:

  • 如果我使用向量,并且我想对所有列进行排序,我会这样做:sort(vect[0].begin(), vect[n-1].end()); ?
  • 对于按列排序,您应该创建另一个矩阵,其中行作为原始矩阵的列。然后按行对这个新矩阵进行排序,并对这个矩阵进行转置。
  • 关键是你只能对一个向量进行排序。(只对矩阵的行)
  • 在排序函数中,不能使用你曾经使用过的语法。
猜你喜欢
  • 2014-08-12
  • 2012-06-11
  • 1970-01-01
  • 1970-01-01
  • 2014-06-02
  • 1970-01-01
  • 2018-10-13
  • 2019-04-12
  • 1970-01-01
相关资源
最近更新 更多