updated with a variadic version
1. Simple, explicit code
class MyClass {
public:
vector<vector<vector<MapCell>>> m;
MyClass(int size_x, int size_y, int size_z)
: m(size_x,
vector<vector<MapCell> >(
size_y,
vector<MapCell>(size_z)
)
) {
}
};
2. With a helper
class MyClass {
vector<vector<vector<MapCell>>> m;
public:
MyClass(int size_x, int size_y, int size_z)
: m(Dim(size_z, Dim(size_y, Dim(size_x, MapCell())))) {
}
private:
template <typename T>
static std::vector<T> Dim(size_t n, T&& v) {
return std::vector<T>(n, std::move(v));
}
};
3. With a variadic helper
Because variadics are funadic! here is a version using variadics to make things ... prettier (depending on taste):
struct MyClass
{
vector<vector<vector<MapCell>>> m;
MyClass(int size_x, int size_y, int size_z)
: m(vec_matrix(MapCell(), size_z, size_y, size_x))
{ }
private:
template <typename T> static std::vector<T> vec_matrix(T v, size_t n) {
return { n, std::move(v) };
}
template <typename T, typename... Dim> static auto vec_matrix(T v, size_t n, Dim... other)
-> std::vector<decltype(vec_matrix(v, other...))> {
return { n, vec_matrix(v, other...) };
}
};
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:
#include <iostream>
#include <vector>
#include <boost/spirit/include/karma.hpp> // for debug output only
using namespace std;
struct MapCell
{
friend std::ostream& operator <<(std::ostream& os, MapCell const&)
{ return os << "."; }
};
struct MyClass
{
vector<vector<vector<MapCell>>> m;
MyClass(int size_x, int size_y, int size_z)
: m(vec_matrix(MapCell(), size_z, size_y, size_x))
{ }
private:
///////////////////////////////////////////////////
// variadics are funadic!
template <typename T> static std::vector<T> vec_matrix(T v, size_t n)
{
return { n, std::move(v) };
}
template <typename T, typename... Dim> static auto vec_matrix(T v, size_t n, Dim... other)
-> std::vector<decltype(vec_matrix(v, other...))>
{
return { n, vec_matrix(v, other...) };
}
////////////
};
int main()
{
MyClass a(4,5,2);
using namespace boost::spirit::karma;
std::cout
<< format(stream % ' ' % eol % "\n-------\n", a.m)
<< std::endl;
}