简体   繁体   English

C ++传递向量 <vector<STRUCT> &gt;用于修改

[英]C++ Passing a vector<vector<STRUCT> > for modifying

let's say I have a 假设我有一个

vector<vector<foobar> > vector2D(3);
for(int i=0;i<3;i++)
   vector2D[i].resize(3);

So, a 3x3 vector containing 9 elements of type foobar in total. 因此,一个总共包含9个foobar类型元素的3x3向量。

I know want to pass "vector2D" to a function to modify some values in "vector2D". 我知道要将“ vector2D”传递给函数以修改“ vector2D”中的某些值。 For example, if foobar contains 例如,如果foobar包含

struct foobar{
       int *someArray;
       bool someBool;
}

I want to pass "vector2D" to a function that modifies vector2D like this: 我想将“ vector2D”传递给修改vector2D的函数,如下所示:

vector2D[0][0].someArray = new int[100];
vector2D[0][0].someArray[49] = 1;

The function shouldn't return anything (call by reference). 该函数不应返回任何内容(通过引用调用)。

Is this even possible? 这甚至可能吗?

Yes, it's possible. 是的,这是可能的。 You just need to pass it in as a non-const reference. 您只需要将其作为非常量引用传递即可。 Something like: 就像是:

void ModifyVector( vector< vector< foobar > > & v )
{
    v[0][0].someArray = new int[100];
    v[0][0].someArray[49] = 1;
}

vector<vector<foobar> > vector2D(3);
ModifyVector( vector2D );

One further note: you probably should implement the copy constructor for your foobar struct if you're using it within a vector. 进一步说明:如果在向量中使用它,则可能应该为foobar结构实现copy构造函数。

Sure, just pass your vector2D by reference: 当然,只需通过引用传递您的vector2D:

void foo(vector<vector<foobar> >& v)
{
    v[0].resize(3);
    v[0][0].someArray = new int[100];
    v[0][0].someArray[49] = 1
}

and call it as: 并将其称为:

vector<vector<foobar> > vector2D(3);
foo(vector2D);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM