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

Правка en1, от 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.

Теги vector, c++ stl

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский AQZZ 2020-07-17 06:17:10 894 Initial revision (published)