将数据从一个矩阵复制到另一个矩阵 [英] Copy data from one matrix to another

查看:887
本文介绍了将数据从一个矩阵复制到另一个矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,我试图将数据从一个矩阵复制到另一个矩阵。我的代码如下:

  int data [height] [width] 
void MyCode :: setData(int newData [height] [width])
{
for(int i = 0; i< height; i ++)
{
for(int j = 0; j< width; j ++)
{
data [i] [j] = newData [i] [j]
}
}
}

for循环太费时,代码停在这里(也许内存是重载的,我正在读取视频帧)。我想知道如何使用指针:

  int * data [height] [width] 
void MyCode :: setData(int * newData [height] [width])
{
data = newData;
}

但它没有工作,我不知道原因。有人可以建议我一个更好的解决方案吗?

解决方案

一个方法是使用一个宽度为* height的1D数组。这样你可以很容易地memcpy之间的数据两个。



它很容易从一行和列的工作,一维数组中的最终位置是通过执行以下操作:

  int index = column +(row * width); 

编辑:如果必须使用2D数组,那么必须知道其中一个尺寸。 >

因此,您可以执行以下操作:

  int data [height]宽度]; 
void MyCode :: setData(int(* newData)[width])
{
for(int i = 0; i< height; i ++)
{
for(int j = 0; j< width; j ++)
{
data [i] [j] = newData [i] [j]
}
}
}

关闭使用像基于模板的解决方案或类似的东西,虽然如果你传递一个数组的错误的高度尺寸,你会得到问题,编译器不会捕捉它。



有大量的模板矩阵库。例如:



http:// sourceforge。 net / projects / tmv-cpp /


In C++, I am trying to copy data from one matrix to another. My code is as follows:

int data[height][width];
void MyCode::setData ( int newData[height][width] )
{   
    for ( int i = 0; i < height; i ++ )
    {
        for ( int j = 0; j < width; j ++ )
        {
            data[i][j] = newData[i][j];
        }   
    }       
}

My problem here is, these "for" loops are too time consuming, and the code stops just here (maybe the memory is overloaded, I am reading video frames). I wondered about using pointers, like this:

int* data[height][width];
void MyCode::setData ( int* newData[height][width] )
{   
     data = newData;
}

But it didn't work, I don't know the reason. Could someone suggest me a better solution for this?

解决方案

One way round this is to use a 1D array that is width * height in size. This way you can easily memcpy the data between the two.

Its easy to work out from a row and column what the eventual position in the 1D array is by doing the following:

int index = column + (row * width);

Edit: If you must use a 2D array then one of the dimensions MUST be known.

As such you can do the following:

int data[height][width];
void MyCode::setData ( int (*newData)[width] )
{   
    for ( int i = 0; i < height; i ++ )
    {
        for ( int j = 0; j < width; j ++ )
        {
            data[i][j] = newData[i][j];
        }   
    }       
}

In C++ you really are better off using something like a template based solution or such like though as if you pass in an array with the wrong height dimension you will get problems and the compiler will not catch it.

There are plenty of template matrix libraries around. For example:

http://sourceforge.net/projects/tmv-cpp/

这篇关于将数据从一个矩阵复制到另一个矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆