fork download
  1. #include<vector>
  2. #include<iostream>
  3. using std::size_t;
  4. using std::cout;
  5.  
  6. // Creating a multidimensional container (e.g. `vector`, `map`)
  7. template<template<typename...> class Container,
  8. typename T,
  9. size_t DIMENSION>
  10. struct MultiDimensional
  11. {
  12. using internal = MultiDimensional<Container, T, DIMENSION-1>;
  13. using type = Container<typename internal::type>;
  14.  
  15. template<typename... Args>
  16. static
  17. type Generate (const size_t size, Args... sizes)
  18. {
  19. return type(size, internal::Generate(sizes...));
  20. }
  21. };
  22.  
  23. // Last dimension overload
  24. template<template<typename...> class Container,
  25. typename T>
  26. struct MultiDimensional<Container, T, 1>
  27. {
  28. using internal = T;
  29. using type = Container<T>;
  30.  
  31. static
  32. type Generate (const size_t size)
  33. {
  34. return type(size);
  35. }
  36. };
  37.  
  38. // Wrapper for the specific requirement of creating a multidimensional `std::vector`
  39. template<typename T,
  40. typename... Args>
  41. auto make_vector(Args... sizes)
  42. -> typename MultiDimensional<std::vector, T, sizeof...(sizes)>::type
  43. {
  44. return MultiDimensional<std::vector, T, sizeof...(sizes)>::Generate(sizes...);
  45. }
  46.  
  47. int main ()
  48. {
  49. size_t n = 5;
  50. auto v3 = make_vector<int>(n+1, n*2, n*3);
  51. cout << "v3.size() = " << v3.size() << "\n";
  52. cout << "v3.back().size() = " << v3.back().size() << "\n";
  53. cout << "v3.back().back().size() = " << v3.back().back().size() << "\n";
  54. }
  55.  
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
v3.size() = 6
v3.back().size() = 10
v3.back().back().size() = 15