C++中的可变大小数组
Variable size array in C++
这很有趣。我想制作一个 2D 数组,其中一个维度是一个变量。这是我的代码:
int main(void) {
const int rows = numlines("health.txt");
float data[rows][5] = {0};
readIntoArray(data, 5, rows, "health.txt");
return 0;
}
第 3 行"行"带有错误下划线。它说:"表达式必须有一个常量值。显然,其他人在这些情况下使用const
是有效的。但是我的工作方式可能不同,因为我的变量是由函数定义的。这是该函数:
int numlines(string filename) {
int number_of_lines = 0;
ifstream fin(filename);
string line;
while (getline(fin, line)) {
++number_of_lines;
}
return number_of_lines;
}
我尝试了以下其他建议,并使我的代码遵循以下格式:
(将第一个代码块的第 2 行和第 3 行替换为此代码块。
int rows = numlines("health.txt");
float **data;
data = new float*[rows]; //The height is defined by the function
for (int i = 0; i < rows; i++) {
data[i] = new float[5]; //The width is 5
}
但这会导致第一个代码块的第 4 行中的"数据"出错。错误是 Argument of type "float**" is incompatible with parameter of type "float (*)[5]"
。以下是相关函数的第一行:
void readIntoArray(float data[][MAXCOLUMNS], int arrayX, int arrayY, string filename)
MAXCOLUMNS
#define
d 为 5。
如何在不产生错误的情况下将 2D 数组传递到函数中?
我不是 c++ 方面最有经验的人,所以我可能会错过一些明显的东西。
两者之间存在差异:
const int rows = numlines("health.txt");
和
const int rows = 20;
在这两种情况下,变量的值一旦初始化就无法修改。不同之处在于,在第一种情况下,该值在运行时之前是已知的,而在第二种情况下,该值在编译时是已知的。
在C++中,只有在编译时已知数组的值时,才能使用变量声明数组。
这就解释了为什么你不能使用:
const int rows = numlines("health.txt");
float data[rows][5] = {0};
但您可以使用:
const int rows = 20;
float data[rows][5] = {0};
您可以通过使用 std::vector
s 的std::vector
轻松解决此问题。
const int rows = numlines("health.txt");
std::vector<std::vector<float>> data(rows, std::vector<float>(5));
既然知道内部数组的大小,你也可以std::array
.这将使声明更简单一些。
std::vector<std::array<float, 5>> data(rows);
在C++中,您可以使用"std::vector
只需学习如何使用STL,它将简化您的工作。
您可以使用 alloca 来实现等效的可变长度数组:
float (*data)[5] = (float (*)[5]) _alloca(rows * 5 * sizeof(float));
这将分配本地(堆栈(空间并将数据设置为指向浮点数矩阵的第一行(包含 5 列(。5 可以用常量代替。然后,您可以像使用普通局部矩阵一样使用数据,data[ i ][ j ] ... 。根据编译器的不同,名称可能是 alloca(( 而不是 _alloca((,并且可能不需要强制转换(float (*([5](。
由于这是本地分配,因此在函数退出时会自动释放。
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 声明后,gcc 的动态大小数组是否与标准数组有效相同?
- 将 int 数组转换为带有小数C++的双精度数组
- 如何将大括号初始值设定项用于动态大小数组和新数组?
- 对未知大小数组的引用的列表初始化:它是否应该推断数组大小?
- 返回指向固定大小数组C++的数组的指针
- 如何将小数数组转换为二进制数数组
- 对指向固定大小数组的指针数组的内存分配的解释
- 在 C++ 中创建固定大小的 int 数组的动态大小数组