AQZZ's blog

By AQZZ, history, 4 years ago, In English

After searching online and doing some modifications, I found a way to create a multidimensional vector with arbitrary dimensions in C++14:

// Easily create k-dimensional vectors (C++14).
template <class T>
vector<T> create(size_t size, T initialValue) {
    return vector<T>(size, initialValue);
}

template <class T, class... Args>
auto create(size_t head, Args&&... tail) {
    auto inner = create<T>(tail...);
    return vector<decltype(inner)>(head, inner);
}

Usage:

auto dp = create<long long>(n, m, k, 1LL); // Makes an n by m by k vector filled with ones.
auto adj = create<int>(n + 1, 0, 0); // Creates the adjacency lists for a graph of n vertices.

The last argument must be of type T, otherwise there will be a compile time error. Any improvements are appreciated.

  • Vote: I like it
  • 0
  • Vote: I do not like it