C++ 如何将2D矩阵的1列传递给C/C+中的函数+;
我有一个2D C样式的数组,我只需要将其中的一列传递给一个函数。我该怎么做C++ 如何将2D矩阵的1列传递给C/C+中的函数+;,c++,c,arrays,multidimensional-array,C++,C,Arrays,Multidimensional Array,我有一个2D C样式的数组,我只需要将其中的一列传递给一个函数。我该怎么做 基本上,我需要MATLAB命令的C/C++等价物A[:,j],它将给我一个列向量。考虑到您的2d阵列,是否可以在C/C++中实现此功能?: std::vector<std::vector<int> > *array = new std::vector<std::vector<int> >; std::list myCol; ... //fill your array /
基本上,我需要MATLAB命令的C/C++等价物
A[:,j]
,它将给我一个列向量。考虑到您的2d阵列,是否可以在C/C++中实现此功能?:
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]]
std::vector*数组=新的std::vector;
std::list myCol;
... //填充你的数组
//在这里,我们使用迭代器遍历每一行
用于(自动it=array->begin();it!=array->end();++it)
//然后我们访问此行的一列的值
霉菌推回(它[列]);
//MyCol将用col值填充
对于col=1,myCol=[8,3,1,4]
\/
它->[[2,8,4,3],
\/ [6, 3, 9, 6],
[9, 1, 3, 3],
[2, 4, 2, 7]]
int colsum(int*a,int行,int列)
{
int i;
整数和=0;
对于(i=0;i
它并不是传递列,而是传递一个指向数组开头的指针,然后指示数组有多少行以及需要关注的列。您有3个选项
1) 传递指向对象的指针(将其移动到目标列的第一个元素后)
twoDArray[0][column]
现在可以计算此列的下一项(通过跳过元素)
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
}
custom2DArray->getCol(1);
.
.
.
给你的包装分类{
私人:
自动数组=新整数[10][10];
公众:
向量getCol(int-col);
}
YourWrapper::向量getCol(int col){
//迭代2d数组(如选项1)并插入值
//在向量和返回中
}
3) 改用一维数组。你可以很容易地得到这些信息。通过跳转行并访问所需列的值。(仅为了提及而提及,不要将其与我对立)最好的方法是将指针传递到列中的第一个元素,并以行长度的增量向前跳转数组。你熟悉指针吗?转置矩阵并传递它row@POW矩阵太大了,我不想转置它。这会影响我的运行时间。@P0W矩阵转置是一个$O(n^2)$操作,不必要。@VivekVK您标记了您的问题
c++
,但您使用了术语数组,在代码或C++容器中使用C数组吗?不是行迭代吗?我反复遍历行,但总是在“代码> COLL/CONDEX>索引下得到值。这是一个很好的解决方案,但是我必须做O(n)操作。我买不起。这里我的N太大了。或者,您可以定义colsum来接受指向列的第一个元素(a+colnum)的指针,并忽略列号传递。将函数调用为colsum(a+colnum,rows);非常感谢。我想,通过计算所需的行号,你的答案仍然可以更快。(如访问1D阵列)不错的选择。将选择第一个选项,因为它在计算上很便宜。
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
}