记住
过早的优化是万恶之源
编写可读代码,当应用程序不够有效时,然后对其进行分析,您会看到瓶颈在哪里,但在这一点上,我几乎可以肯定您没有使用 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;
}