cla*_*nes 2 c++ vector pass-by-reference
让我说我有一个
vector<vector<foobar> > vector2D(3);
for(int i=0;i<3;i++)
vector2D[i].resize(3);
Run Code Online (Sandbox Code Playgroud)
因此,总共包含9种foobar元素的3x3载体.
我知道想要将"vector2D"传递给一个函数来修改"vector2D"中的一些值.例如,如果foobar包含
struct foobar{
int *someArray;
bool someBool;
}
Run Code Online (Sandbox Code Playgroud)
我想将"vector2D"传递给修改vector2D的函数,如下所示:
vector2D[0][0].someArray = new int[100];
vector2D[0][0].someArray[49] = 1;
Run Code Online (Sandbox Code Playgroud)
该函数不应返回任何内容(通过引用调用).
这甚至可能吗?
是的,这是可能的.您只需要将其作为非const引用传递.就像是:
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 );
Run Code Online (Sandbox Code Playgroud)
还有一点需要注意:foobar如果你在向量中使用它,你可能应该为你的struct 实现复制构造函数.