I have the following code which seems to work:
class MapCell
{
public:
int x, y, z;
};
void Test3DVector(int size_x, int size_y, int size_z)
{
vector< vector< vector<MapCell> > > m(size_x, vector<vector<MapCell>>(size_y, vector<MapCell>(size_z)));
for (int x = 0; x < size_x; ++x)
{
for (int y = 0; y < size_y; ++y)
{
for (int z = 0; z < size_z; ++z)
{
m[x][y][z].x = x;
m[x][y][z].y = y;
m[x][y][z].z = z;
}
}
}
}
I want to write a class that has the 3D vector as a member variable, with the dimensions set in the constructor, like so:
class MyClass
{
public:
vector< vector< vector<MapCell>>> m; // I'm not sure how to write this
MyClass::MyClass(int size_x, int size_y, int size_z)
{
// Do the same initialization as Test3DVector did.
}
};
So that I can do something like this:
void SomeFunction()
{
MyClass grid(5, 5, 5);
cout << grid->m[1][3][2].x << grid->m[1][3][2].y << grid->m[1][3][2].z << endl;
// Should output 132
}
What is the best way to do this? When the vectors become very large are there any common mistakes that I should avoid to get the best speed?
updated with a variadic version
1. Simple, explicit code
2. With a helper
3. With a variadic helper
Because variadics are funadic! here is a version using variadics to make things … prettier (depending on taste):
PS. I have slightly edited the code to be more standards-compliant. There is a subtle issue with templates and trailing-return-type that refers to an overload of the same name.
For a nice breakdown of the issue here, see this discussion bookmark in chat
In case your compiler doesn’t believe it should work, see it live on gcc 4.7.2. It uses boost only to format the output:
Full code to avoid link-rot on SO: