How to easily create a multidimensional vector with an initial value.

Revision en1, by AQZZ, 2020-07-17 06:17:10

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.

Tags vector, c++ stl

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English AQZZ 2020-07-17 06:17:10 894 Initial revision (published)