4

I can create a 2D array of size n*mby doing: vector< vector< int > > foo(n, vector< int > (m)).

Suppose that at runtime I'm given a variable number of values, e.g. v_1, v_2, v_3, ..., v_k and want to create the following:

vector< vector< ... vector< int > ... > > foo(v_1, vector< ... > (v_2, vector< ... > ..));

In other words create a multidimensional array of size v_1* v_2 * v_3 ... *v_k. How can I do this? Is this possible?

4

2 に答える 2

5

boost::variantこれを処理できる が必要です。コンテンツを任意にネストできる recursive_wrapper を作成できます。大きなサイズの 1 つのフラットな配列を使用する方法や、継承と動的割り当てを使用する方法など、他の方法もありますが、かなり手間がかかります。

typedef boost::variant<
    int,
    std::vector<boost::recursive_variant_>
> variant;

int main() {
    std::vector<variant> var; // Assume at least 1 dimension
}
于 2013-01-26T13:33:12.357 に答える
4

これはできません。コンパイル時にデータ型を設定する必要があります。[i1][i2][...]そうは言っても、正しい合計要素数を持つ単一の配列を使用し、論理が say で見つかるようにマッピングを作成することは非常に実用的です[i1*v2*v3...vk + i2*v3..vk + ...]

于 2013-01-26T13:28:39.740 に答える