Блог пользователя AQZZ

Автор AQZZ, история, 4 года назад, По-английски

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.

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится