开发者

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.

I know want to pass "vector2D" to a function to modify some values in "vector2D". For example, if foobar contains

struct foobar{
       int *someArray;
       bool someBool;
}

I want to pass "vector2D" to a function that modifies vector2D like this:

vector2D[0][0].someArray = new int[100];
vector2D[0][0].someArr开发者_如何学JAVAay[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.


Sure, just pass your vector2D by reference:

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜