如何创建二维矩阵 C++ 的水平镜像逆?

How to create the horizontally mirror inverse of a 2d matrix c++?

例如,如果输入是:

21 26 31 36
22 27 32 37
23 28 33 38
24 29 34 39
25 30 35 40

输出应该是:

25 30 35 40
24 29 34 39
23 28 33 38
22 27 32 37
21 26 31 36

所有行交换直到中间一行。

第一行应与最后一行交换,第二行与最后一行交换,依此类推...

这是我的代码:

int A[100][100] = { 0 };
int n, m;
std::cin >> n >> m;


for (int k = 0, j = n - 1; k < j; k++, --j)
     std::swap(A[k], A[j]);

number of rows(n), columns(m), for n, m < 100 它向我展示了与之前相同的矩阵。

您可以使用标准算法 std::swap_ranges 或编写 "manually" 循环来交换二维数组。

这是一个演示程序。

#include <iostream>
#include <iterator>
#include <algorithm>

int main() 
{
    const size_t M = 5, N = 4;
    int a[M][N] = 
    {
        { 21, 26, 31, 36 },
        { 22, 27, 32, 37 },
        { 23, 28, 33, 38 },
        { 24, 29, 34, 39 },
        { 25, 30, 35, 40 }
    };

    for ( const auto &row : a )
    {
        for ( const auto &item : row )
        {
            std::cout << item << ' ';
        }
        std::cout << '\n';
    }
    std::cout << '\n';

    std::swap_ranges( std::begin( a ), std::next( std::begin( a ), M / 2 ), 
                      std::rbegin( a ) );

    for ( const auto &row : a )
    {
        for ( const auto &item : row )
        {
            std::cout << item << ' ';
        }
        std::cout << '\n';
    }
    std::cout << '\n';

    for ( std::size_t i = 0; i < N / 2; i++ )
    {
        std::swap( a[i], a[M - i - 1] );
    }

    for ( const auto &row : a )
    {
        for ( const auto &item : row )
        {
            std::cout << item << ' ';
        }
        std::cout << '\n';
    }
    std::cout << '\n';

    return 0;
}

它的输出是

21 26 31 36 
22 27 32 37 
23 28 33 38 
24 29 34 39 
25 30 35 40 

25 30 35 40 
24 29 34 39 
23 28 33 38 
22 27 32 37 
21 26 31 36 

21 26 31 36 
22 27 32 37 
23 28 33 38 
24 29 34 39 
25 30 35 40 

请注意可变长度数组不是标准的 C++ 功能。这意味着数组的大小应在编译时已知。如果您希望由用户输入尺码,请使用标准 class 模板 std::vector.

如果您已经定义了一个数组,其中包含其大小的一些最大值并且用户可以指定其子数组,那么该数组应该至少被零初始化

您可以使用 std::reverse:

交换二维数组
#include <algorithm>
#include <iostream>

int main()
{
    int A[100][100] = { {21, 26, 31, 36},
                        {22, 27, 32, 37},
                        {23, 28, 33, 38},
                        {24, 29, 34, 39},
                        {25, 30, 35, 40} };

    std::reverse(&A[0], &A[5]);  // Starting and ending ranges are &A[0] and &A[5]

    // Output results
    for (int i = 0; i < 5; ++i)
    {
        for (int j = 0; j < 4; ++j)
            std::cout << A[i][j] << " ";
        std::cout << "\n";
    }
}

输出:

25 30 35 40 
24 29 34 39 
23 28 33 38 
22 27 32 37 
21 26 31 36