【问题标题】:How I can sort two dimensional array's columns?如何对二维数组的列进行排序?
【发布时间】:2022-01-02 03:27:12
【问题描述】:

大家好,我想对二维数组的列进行排序。我想从用户那里获取数组的维度和元素并将其显示为矩阵。然后减去同一个数组的排序形式。我们只需要对数组的列进行排序。请帮忙。

类似的东西

{{0, 1, 3},
{6, 0, 8},
{5, 9, 2}}


{{0, 0, 2},
{5, 1, 3},
{6, 9, 8}}

为此,我用 C++ 编写了代码,我可以对数组的第一列进行排序并显示它,但我不能执行其他列。为此我向您提出上诉。

#include <iostream>
using namespace std;
int main()
{
    int column, row;
    cout << "Column = ";
    cin >> column;
    cout << "Row = ";
    cin >> row;
    int array[column][row];
    int sortedarray[column];
    for (int z = 0; z < column; z++) {
        for (int a = 0; a < row; a++) {
            cin >> array[z][a];
        }
    }
    for (int i = 0; i < column; i++) {
        sortedarray[i] = array[i][0];
    }

    cout << "\n";
    for (int y = 0; y < column; y++) {
        for (int i = 0; i < row; i++) {
            cout << array[y][i] << "    ";
        }
        cout << endl;
    }
    cout << "\n";

    int temp = 0;
    for (int i = 1; i < column; i++)
        for (int j = 0; j < column - i; j++) {
            if (sortedarray[j] > sortedarray[j + 1]) {
                temp = sortedarray[j];
                sortedarray[j] = sortedarray[j + 1];
                sortedarray[j + 1] = temp;
            }
        }
    cout << "COUT sorted array \n ";
    for (int i = 0; i < column; i++) {
        cout << sortedarray[i] << "  ";
    }
}

【问题讨论】:

  • 我不明白您的示例,您希望如何对它们进行排序? list_name.sort(key=lambda x:x[1],reverse=True)这是python代码,会根据第二列对多维数组进行降序排序

标签: c++ arrays sorting multidimensional-array


【解决方案1】:

据我了解,您需要以下内容:

1 5 6

2 8 4

9 7 3

分类为:

1 2 3

4 5 6

7 8 9

最简单的方法是您必须将二维数组映射为一维数组 - “1 5 6 2 8 4 9 7 3”,使用最优算法对它们进行排序。这将返回“ 1 2 3 4 5 6 7 8 9 ”,然后将其从一维数组映射回二维数组。

实际上,您可以实现任何排序,这取决于您的映射。

你甚至可以实现这样的目标

1 4 7

2 5 8

3 6 9

您需要的是从二维到一维的映射。

【讨论】:

  • 是的,我想按照你上次展示的那样做。 1 4 7 2 5 8 3 6 9 我想照你说的做,但我做不到。我无法将二维数组移动到一维数组。要从二维数组切换到一维数组,需要两个嵌套的 for 循环。我这样做了,但我可以为 (int i) 写其中一个元素我在哪里可以写第二个 (int j)?请帮忙。
  • 我想要 1 4 7 2 5 8 3 6 9 。我应该使用哪个映射? @Furqan
【解决方案2】:

这是我的解决方案:

#include <iostream>
#include <iomanip>
#include <vector>
#include <tuple>

int getDigitCount( int num )
{
    num = abs( num );

    return ( num < 10    ? 1 :
           ( num < 100    ? 2 :
           ( num < 1000    ? 3 :
           ( num < 10'000   ? 4 :
           ( num < 100'000   ? 5 :
           ( num < 1'000'000  ? 6 :
           ( num < 10'000'000  ? 7 :
           ( num < 100'000'000  ? 8 :
           ( num < 1'000'000'000 ? 9 :
                                    10 )))))))));
}

void printMatrix( const std::vector<int>& array,
                  const std::tuple< const size_t, const size_t >& dimensions, const int maxDigitCount )
{
    const auto& [ rowCount, colCount ] { dimensions };

    std::cout << '\n' << "    \\ Column  ";

    for ( size_t colNumber = 0; colNumber < colCount; ++colNumber )
    {
        std::cout << std::left << std::setw( maxDigitCount + 2 ) << std::setfill(' ') << colNumber;
    }

    std::cout << '\n' << "Row  \\" << '\n' << '\n';

    for ( size_t idx = 0; idx < rowCount * colCount; ++idx )
    {
        if ( ( idx ) % ( colCount ) == 0 )
        {
            std::cout << " " << ( idx ) / ( colCount ) << "            ";
        }

        std::cout << std::left << std::setw( maxDigitCount + 2 ) << std::setfill(' ') << array[ idx ];

        if ( ( idx + 1 ) % ( colCount ) == 0 )
        {
            std::cout << '\n' << '\n';
        }
    }
}

// get row count and column count from the user
auto getDimensions( )
{
    constexpr int MIN_ALLOWED_ROW_COUNT { 1 };
    constexpr int MIN_ALLOWED_COL_COUNT { 1 };
    constexpr int MAX_ALLOWED_ROW_COUNT { 50 };
    constexpr int MAX_ALLOWED_COL_COUNT { 50 };

    int inputRowCount { };
    int inputColCount { };

    do
    {
        std::cout << "Enter row count: ";
        std::cin >> inputRowCount;

        std::cout << "Enter column count: ";
        std::cin >> inputColCount;

    } while ( inputRowCount < MIN_ALLOWED_ROW_COUNT || inputColCount < MIN_ALLOWED_COL_COUNT ||
              inputRowCount > MAX_ALLOWED_ROW_COUNT || inputColCount > MAX_ALLOWED_COL_COUNT );

    return std::make_tuple<int, int>( std::move( inputRowCount ), std::move( inputColCount ) );
}

// get user input ( user's matrix ) and populate the array
void getArrayElements( std::vector<int>& array, int& maxDigitCount )
{
    for ( std::vector<int>::iterator it = array.begin( ); it != array.end( ); ++it )
    {
        std::cin >> *it;

        if ( getDigitCount( *it ) > maxDigitCount )
        {
            maxDigitCount = getDigitCount( *it );
        }
    }
}

// bubble sort the array
void bubbleSortArray( std::vector<int>& array, const size_t& elementCount )
{
    for ( size_t iterCount = 0; iterCount < elementCount - 1; ++iterCount )
    {
        for ( size_t idx = 0; idx < ( elementCount - 1 - iterCount  ); ++idx )
        {
            if ( array[ idx ] > array[ idx + 1 ] )
            {
                int temp = array[ idx ];
                array[ idx ] = array[ idx + 1 ];
                array[ idx + 1 ] = temp;
            }
        }
    }
}

// transpose 1D array and store in 1D transposedArray
void transposeMatrix( std::vector<int>& array, std::vector<int>& transposedArray,
                      const std::tuple< const size_t, const size_t >& dimensions )
{
    size_t row { };
    size_t col { };

    const auto& [ rowCount, colCount ] { dimensions };

    for ( size_t idx = 0; idx < rowCount * colCount; ++idx )
    {
        if ( col == colCount )
        {
            ++row;
            col = 0;
        }

        size_t newIdx { row + ( col * rowCount ) };

        transposedArray[ newIdx ] = array[ idx ];

        ++col;
    }
}

void launch( )
{
    const auto [ inputRowCount, inputColCount ] = getDimensions( );

    const size_t rowCount { static_cast<unsigned int>( inputRowCount ) };
    const size_t colCount { static_cast<unsigned int>( inputColCount ) };
    const std::tuple< const size_t, const size_t > dimensions( std::move( rowCount ),
                                                               std::move( colCount ) );
    const size_t elementCount { rowCount * colCount };

    std::vector<int> array( elementCount ); // the 1D array for storing the user's matrix

    int maxDigitCount { };
    getArrayElements( array, maxDigitCount );

    std::cout << "\nOriginal 2D array:\n"; // print out the array

    printMatrix( array, dimensions, maxDigitCount );

    bubbleSortArray( array, elementCount );

    std::cout << "\nSorted 2D array:\n"; // print out the sorted array

    printMatrix( array, dimensions, maxDigitCount );

    std::vector<int> transposedArray( elementCount );

    transposeMatrix( array, transposedArray, dimensions );

    std::cout << "\nTransposed sorted 2D array:\n"; // print out the transposed sorted array

    printMatrix( transposedArray, std::make_tuple< const size_t, const size_t >
               ( std::move( colCount ), std::move( rowCount ) ), maxDigitCount );
}

int main()
{
    launch( );

    return 0;
}

还有一个示例输入/输出:

Enter row count: 5
Enter column count: 4
1  6  11  16
2  7  12  17
3  8  13  18
4  9  14  19
5  10 15  20

Original 2D array:

    \ Column  0   1   2   3
Row  \

 0            1   6   11  16

 1            2   7   12  17

 2            3   8   13  18

 3            4   9   14  19

 4            5   10  15  20


Sorted 2D array:

    \ Column  0   1   2   3
Row  \

 0            1   2   3   4

 1            5   6   7   8

 2            9   10  11  12

 3            13  14  15  16

 4            17  18  19  20


Transposed sorted 2D array:

    \ Column  0   1   2   3   4
Row  \

 0            1   5   9   13  17

 1            2   6   10  14  18

 2            3   7   11  15  19

 3            4   8   12  16  20

转置的排序二维数组是您想要获得的输出(基于我对您问题的理解)。

此外,顶部还有一个函数getDigitCount,用于计算一个数字在所有用户提供的数字之间的最大位数以进行字符串格式化(使用std::setw)。

【讨论】:

    猜你喜欢
    • 2016-01-08
    • 2013-09-13
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 2015-09-17
    相关资源
    最近更新 更多