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

查看:26
本文介绍了最简单的二维数组,使用 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天全站免登陆