[英]Passing a Vector of a Vector with variables to a function
I was trying to create an array with variables for the size(ie array[x][y]), which won't work. 我试图创建一个带有大小变量的数组(即array [x] [y]),这是行不通的。 I stumbled upon a post that suggested using a vector of a vector: 我偶然发现了一条建议使用向量的向量的帖子:
vector<vector<int> > grid(GetGridXComponent(), vector<int>(GetGridYComponent()));
The GetGridXComponent() and GetGridYComponent() retrieves private variables from a class. GetGridXComponent()和GetGridYComponent()从类中检索私有变量。
The code works inside the function, but I need to be able to access the vector, "grid", outside of the class. 该代码在函数内部起作用,但是我需要能够在类外部访问向量“ grid”。 To do this, I tried to create a public instance: 为此,我尝试创建一个公共实例:
vector<vector<int> > grid(GetGridXComponent(), vector<int>(GetGridYComponent()));
But of course, GetGridXComponent() and GetGridYComponent() won't work because it thinks that I'm creating a function and wants me to declare a type for GetGridXComponent(). 但是,当然,GetGridXComponent()和GetGridYComponent()无法工作,因为它认为我正在创建一个函数,并希望我为GetGridXComponent()声明类型。
Is there a way of going about this? 有办法解决吗? Am I making it harder than it needs to be? 我是否使它变得比需要的难? Thanks in advance. 提前致谢。
Class Simulator
{
private:
int s_iGridXComponent;
int s_iGridYComponent;
public:
Simulator();
~Simulator();
int GetGridXComponent();
int GetGridYComponent();
void Function(vector<vector<int> >&);
vector<vector<int> > pelletGrid(GetGridXComponent(), vector<int>(GetGridYComponent()));
}
void Simulator::Function(vector<vector<int> > &grid)
{
code;
}
Assuming you are just trying to create a class member named pelletGrid
that is a 2D vector it should be just something like: 假设您只是试图创建一个名为pelletGrid
的类成员,该类成员是一个2D向量,则它应该类似于:
class Simulator
{
private:
int s_iGridXComponent;
int s_iGridYComponent;
std::vector<std::vector<int>> pelletGrid;
public:
Simulator(const int x, const int y) :
s_iGridXComponent(x),
s_iGridYComponent(y),
pelletGrid(x, std::vector<int>(y))
{ }
void CreateGrid (const int x, const int y)
{
s_iGridXComponent = x;
s_iGridYComponent = y;
pelletGrid = std::vector<std::vector<int>>(x, std::vector<int>(y));
}
};
You can use either the constructor or the custom method in order to initialize the 2D vector depending on when you know the X/Y dimensions. 您可以使用构造函数或自定义方法来初始化2D向量,具体取决于您何时知道X / Y尺寸。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.