最简单的二维数组,使用g ++,一个可变维度? [英] Simplest 2D array, using g++, with one variable dimension?

查看:263
本文介绍了最简单的二维数组,使用g ++,一个可变维度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个这样的数组:

I would like to make an array like this:

double array[variable][constant];

只有第一个维度是可变的。使用变量作为第一维声明此变量会产生初始化错误。使用指针或其他基本类型是否有一个简单的方法?

Only the first dimension is variable. Declaring this with a variable as the first dimension gives initialization errors. Is there a simple way to do this with pointers or other basic types?

推荐答案

可变长度数组没有在最新的C ++标准。您可以使用 std :: vector 代替

Variable length arrays didn't make it in the latest C++ standard. You can use std::vector instead

std::vector<std::vector<double> > arr;

或者,为了修复例如第二维(在本示例中为10),您可以

Or, to fix for example the second dimension (to 10 in this example), you can do

std::vector<std::array<double, 10> > arr1; // to declare a fixed second dimension

否则,您需要使用旧的指针

Otherwise you need to use old pointers,

double (*arr)[10]; // pointer to array-of-10-doubles

根据@ Chiel的评论,你可以做

In light of @Chiel's comment, to increase performance you can do

typedef double (POD_arr)[10];
std::vector<POD_arr> arr;

以这种方式,所有数据都连续存储在内存中,因此访问应该使用一个简单的 C 数组。

In this way, you have all data stored contiguously in the memory, so access should be as fast as using a plain old C array.

PS:看起来最后一个声明是违反标准, @juanchopanza提到,POD数组不满足要存储在STL数组中的数据的要求(它们是不可分配的)。但是, g ++ 编译上面的2个声明没有任何问题,并且可以在程序中使用它们。但 clang ++ 失败。

PS: it seems that the last declaration is against the standard, since as @juanchopanza mentioned, POD arrays do not satisfy the requirements for data to be stored in an STL array (they are not assignable). However, g++ compiles the above 2 declarations without any problems, and can use them in the program. But clang++ fails though.

这篇关于最简单的二维数组,使用g ++,一个可变维度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆