문제

I am a lazy programmer. I want to use C++ vector to create a multidimensional array. For example, this code create a 3x2 2D array:

int nR = 3;
int nC = 2;
vector<vector<double> > array2D(nR);
for(int c = 0; c < nC; c++)
    array2D.resize(nC, 0);

However, I am too lazy to

  • declare array2D's data type: vector<vector<double> >

C++ auto could solve this problem.

However, I am too lazy to

  • write loop(s) to allocate the space(s) for each object like array2D.

Writing a function could solve this problem.

However, I am too lazy to

  • write each function for each N-dimensional array.
  • write nested N-1 loops for allocating spaces.
  • wirte each function for each data type.

The C++11 variadic template with function recursion could solve this problem. Is it possible ...?

도움이 되었습니까?

해결책

This is what you want. (Tested on Microsoft Visual C++ 2013 Update 1)

#include <iostream>
#include <vector>
using namespace std;

template<class elemType> inline vector<elemType> getArrayND(int dim) {
    // Allocate space and initialize all elements to 0s.
    return vector<elemType>(dim, 0);
}

template<class elemType, class... Dims> inline auto getArrayND(
int dim, Dims... resDims
) -> vector<decltype(getArrayND<elemType>(resDims...))> {
    // Allocate space for this dimension.
    auto parent = vector<decltype(getArrayND<elemType>(resDims...))>(dim);

    // Recursive to next dimension.
    for (int i = 0; i < dim; i++) {
        parent[i] = getArrayND<elemType>(resDims...);
    }
    return parent;
}

int main() {

    auto test3D = getArrayND<double>(2, 3, 4);
    auto test4D = getArrayND<double>(2, 3, 4, 2);
    test3D[0][0][1] = 3;
    test4D[1][2][3][1] = 5;

    cout << test3D[0][0][1] << endl;
    cout << test4D[1][2][3][1] << endl;

    return 0;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top