将bi维的一部分复制到自身上

时间:2016-02-27 03:41:44

标签: c++ c multidimensional-array memcpy

我有一个双维布尔(整数)数组,如下所示:

0 1 0 0
0 0 0 0
0 0 0 0
0 0 0 0

我想说我要复制前2个2节

0 1
0 0

在其余三个象限上,所以它最终看起来如下:

0 1 0 1
0 0 0 0
0 1 0 1
0 0 0 0

我想使用memcpy因为我认为这是最快的方法。在这种情况下我怎么能利用它呢?甚至可以复制二维内容吗?

如果没有,那么我唯一的改变是有一个一维数组,我用N * N索引?

2 个答案:

答案 0 :(得分:0)

多维数组在内存中的布局与一个较长的数组相同。在任何一种情况下,memcpy都不会在这里帮助你(无论如何都是一次通话)。

01010000
01010000
00000000
00000000

虽然在抽象布局中,看起来你可以复制那个方块,但实际上它看起来像是:

01000000010000000000000000000000
^^^^^^^^^^^^

您还必须在第一行包含所有值。

此外,memcpy只能复制源数组的长度。您无法通过一次memcpy调用将4个字节复制到16个字节上。

编辑:在我写这篇文章时,编辑了这个问题来改变这些值。但是,我认为使用原始设置可以更好地说明我的观点。只有在模式正确时才会巧合。

答案 1 :(得分:0)

记住

  

过早优化是万恶之源

编写可读代码,当应用程序不够有效时,然后对其进行分析,你会看到你遇到瓶颈的地方,但此时我几乎可以肯定你没有使用memcpy不会影响那么多如你所愿。

但是...

你标记了C ++,所以这是我简单的可编译C ++示例实现。 它将子矩阵复制到矩阵的末尾(之前没有,所以如果你将通过该子矩阵的起点,例如2,3它不会将它复制到0,0)

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

    using namespace std;

    void copy_submatrix( size_t n, 
                         size_t m, 
                         const pair<size_t, size_t> &from, 
                         const pair<size_t, size_t> &to, 
                         vector<vector<int>> &oryginal_matrix )
    {
        auto begin_y = oryginal_matrix.begin() + from.first;
        auto begin_to_y = oryginal_matrix.begin() + to.first;
        auto end_y = begin_y + m;


        for( ; begin_y != end_y; ++begin_y, ++begin_to_y )
        {
            auto begin_x = (*begin_y).begin() + from.second;
            auto begin_to_x = (*begin_to_y).begin() + to.second;

            copy( begin_x, begin_x + n, begin_to_x );
        }
    }

    void process_matrix( vector<vector<int>> &matrix, 
                         size_t submatrix_n, 
                         size_t submatrix_m )
    {
        for( size_t y = 0; y < matrix.size(); y += submatrix_m )
            for( size_t x = 0; x < matrix.size(); x += submatrix_n )
                copy_submatrix( submatrix_n,
                                submatrix_m,
                                { 0, 0 },
                                { y, x },
                                matrix );
    }

    void print( const vector<vector<int>> &matrix )
    {
        for( const auto &v : matrix )
        {
            copy( v.begin(),
                  v.end(),
                  ostream_iterator<int>( cout, " " ) );

            cout << "\n";
        }
    }

    int main() {
        vector<vector<int>> matrix{ 
            { 0, 1, 0, 0, 0 }, 
            { 0, 0, 0, 0, 0 }, 
            { 0, 0, 0, 0, 0 }, 
            { 0, 0, 0, 0, 0 }, 
            { 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0 }
        };


        cout<<"before: \n";
        print( matrix );

        process_matrix( matrix, 2, 3 );

        cout << "after: \n";
        print( matrix );

        return 0;
    }