如何在C/ c++中传递二维矩阵的1列到函数

How to pass 1 column of a 2D matrix to a function in C/C++

本文关键字:二维 函数 1列 c++      更新时间:2023-10-16

我有一个2D c风格的数组,从中我必须将它的一列传递给函数。我怎么做呢?

基本上,我需要MATLAB命令A[:,j]的C/c++等量物,它会给我一个列向量。在C/c++中可能吗?

你有3个选择,

1)传递一个指针到你的对象(在移动到目标列的第一个元素之后)

twoDArray[0](列)

现在可以计算该列的下一项(通过跳过元素)

2)创建一个包装器类来为您做这些。

custom2DArray->getCol(1);
.
.
.
class YourWrapper{
 private:
   auto array = new int[10][10];
 public:
   vector<int> getCol(int col);
}
YourWrapper:: vector<int> getCol(int col){
  //iterate your 2d array(like in option 1) and insert values 
  //in the vector and return
}

3)使用一维数组代替。你可以很容易地得到这个信息。通过跳过行并访问所需列的值。(为了提而提,别怪我)

int colsum(int *a, int rows, int col)
{
    int i;
    int sum = 0;
    for (i = 0; i < rows; i++)
    {
        sum += *(a + i*rows+col);
    }
    return sum;
}    

int _tmain(int argc, _TCHAR* argv[])
{
    int rows = 2;
    int cols = 2;    
    int i, j;    
    int *a;
    a = (int*)malloc(rows*cols*sizeof(int));
    // This just fills each element of the array with it's column number.
    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < cols; j++)
        {
            *(a+i*rows + j) = j;    
        }
    }
    // Returns the sum of all elements in column 1 (second from left)
    int q = colsum(a, rows, 1);
    printf("%in", q);
    return 0;
}

并不是传递的是列,它传递的是指向数组开头的指针,然后告诉它数组有多少行,应该关注哪一列。

考虑到你的2d数组:

std::vector<std::vector<int> > *array = new std::vector<std::vector<int> >;
std::list myCol;
... //fill your array
//Here we iterate through each row with an iterator
for (auto it = array->begin(); it != array->end(); ++it)
    //Then we access the value of one col of this row
    myCol.push_back(it[col]);
//MyCol will be filled with the col values

        for col = 1, myCol=[8, 3, 1, 4]
        / 
it->[[2, 8, 4, 3],
/   [6, 3, 9, 6],
     [9, 1, 3, 3],
     [2, 4, 2, 7]]