首页 > 解决方案 > 按词法顺序排列二维数组

问题描述

我有一个二维字符数组,我试图按字母顺序排列它们。在每一行中都有一个字符组成的单词,我正在尝试对其进行排序。我做了一些东西,但我不明白为什么这不起作用。如果您对我有解决方案,请解释您在做什么,以了解我为什么不成功。谢谢 !

char matrix[4][5] = {
                {'h','e','l','l','o'},
                {'r','e','a','d','y'},
                {'a','p','p','l','e'},
                {'p','o','i','n','t'},
                
    };
    char temp;
    bool flag = false;

    display(matrix);

    for (int i = 0; i < 4 - 1; i++)
    {
        for (int rows = 0; rows < 10-1; rows++)
    {
        flag = false;
        for (int cols = 0; cols < 5; cols++)
        {
            if (matrix[rows][cols] > matrix[rows + 1][cols])
            {
                flag = true;
                break;
            }
        }
        if (flag)
        {
            for (int index = 0; index < 5; index++)
                {
                        temp=matrix[rows][index];
                        matrix[rows][index]=matrix[rows+1][index];
                        matrix[rows+1][index]=temp;
                }
        }
    }
    }

标签: c++arrayssorting

解决方案


我会发布这个答案,即使它可能不是您想要做的(但会对可能想要以这种方式做事的其他人有所帮助)。

不是对二维数组进行排序,而是不对它进行排序,而是对指向数组的索引数组进行排序。这比试图操纵数组本身要简单得多。

这是一个非常简单的例子:

#include <algorithm>
#include <cstring>
#include <iostream>

int main()
{
    char matrix[4][5] = {
                    {'h','e','l','l','o'},
                    {'r','e','a','d','y'},
                    {'a','p','p','l','e'},
                    {'p','o','i','n','t'},

    };

    // create the indices
    int index[] = { 0,1,2,3 };

    // sort the indices based on the data in the array 
    std::sort(index, index + 4, [&](int n1, int n2) 
          { return strncmp(matrix[n1], matrix[n2], 5) < 0; });

    // Output the results
    for (int i = 0; i < 4; ++i)
    {
        // Note how we access the original matrix using the index array
        std::cout.write(matrix[index[i]], 5);

        std::cout << " -- Using array at row " << index[i] << "\n";                    
   }
}

输出:

apple -- Using array at row 2
hello -- Using array at row 0
point -- Using array at row 3
ready -- Using array at row 1

最终结果表明,如果我们想以排序方式访问数组,索引只是指向将使用的行。原始阵列未调整。


推荐阅读