如何将元素排序到矩阵C++

How to sort elements into C++ matrix?

本文关键字:C++ 排序 元素      更新时间:2023-10-16

我是C++编程新手。我需要对这个矩阵进行排序:

#include <iostream>
#include <iomanip>

#include <cstdlib>
using namespace std;

int main(int argc, char** argv) {
    Mat10 a;
    fillRand(a, 5, 5);
    prnMat(a, 5, 5);
    cout << endl;
    return 0;
}
void fillRand(Mat10 m, int n, int k) {
    for (int i = 0; i < n; i++)      
        for (int j = 0; j < k; j++)
            m[i][j] = rand() % 1000;    
}
void prnMat(Mat10 a, int m, int n) {
    for (int i = 0; i < m; i++) {        
        for (int j = 0; j < n; j++)
            cout << setw(8) << a[i][j];
        cout << endl;
    }
}

我需要从头到尾对矩阵进行排序。最小值必须位于第一列的开头。下一个必须在它下面,依此类推。结果必须是排序矩阵 - 最小数字必须位于左列的开头 - 最大值必须在矩阵的末尾。你能帮忙解决问题吗?

编辑

也许我找到了可能的解决方案:

void sort(int pin[10][2], int n)
{
    int y,d;
    for(int i=0;i<n-1;i++)
    {
        for(int j=0; j<n-1-i; j++)
        {
            if(pin[j+1][1] < pin[j][1])  // swap the elements depending on the second row if the next value is smaller
            {
                y = pin[j][1];
                pin[j][1] = pin[j+1][1];
                pin[j+1][1] = y;
                d = pin[j][0];
                pin[j][0] = pin[j+1][0];
                pin[j+1][0] = d;
            }
            else if(pin[j+1][1] == pin[j][1]) // else if the two elements are equal, sort them depending on the first row
            {
                if(pin[j+1][0] < pin[j][0])
                {
                    y = pin[j][1];
                    pin[j][1] = pin[j+1][1];
                    pin[j+1][1] = y;
                    d = pin[j][0];
                    pin[j][0] = pin[j+1][0];
                    pin[j+1][0] = d;
                }
            }
        }
    }
}

但是由于我是编程新手,我不明白这是解决方案吗?

这里有一个简单的例子:

#include <vector>
#include <algorithm>
using namespace std;
//This is the comparation function needed for sort()
bool compareFunction (int i,int j) 
{ 
    return (i<j); 
}
int main()
{
    //let's say you have this matrix
    int matrix[10][10];
    //filling it with random numbers.
    for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
            matrix[i][j] = rand() % 1000;
    //Now we get all the data from the matrix into a vector.
    std::vector<int> vect;
    for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
            vect.push_back(matrix[i][j]);
    //and sort the vector using standart sort() function
    std::sort( vect.begin(), vect.end(), compareFunction );
    //Finally, we put the data back into the matrix
    for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
            matrix[i][j] = vect.at(i*10 + j);
}

在此之后,矩阵将按排序:

1 2
3 4

如果您希望按排序:

1 3
2 4

只需要将上一个周期中的matrix[i][j]替换为matrix[j][i]

如果您需要阅读有关 sort() 函数的信息,您可以在此处完成希望这有帮助。

您可以简单地在数组上调用 std::sort:

#include <algorithm> // for std::sort
int main() {
  int mat[10][10];
  // fill in the matrix
  ...
  // sort it
  std::sort(&mat[0][0], &mat[0][0]+10*10);
}