C++中的可变大小数组

Variable size array in C++

本文关键字:小数 数组 C++      更新时间:2023-10-16

这很有趣。我想制作一个 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](。

由于这是本地分配,因此在函数退出时会自动释放。