简体   繁体   English

C ++中的可变大小数组

[英]Variable size array in C++

This is interesting. 这是有趣的。 I want to make a 2D array where one of the dimensions is a variable. 我想制作一个二维数组,其中一个维度是一个变量。 Here is my code: 这是我的代码:

int main(void) {
     const int rows = numlines("health.txt");
     float data[rows][5] = {0};
     readIntoArray(data, 5, rows, "health.txt");
     return 0;
}

Line 3 "rows" is underlined with an error. 第3行“行”下划线带有错误。 It says: "Expression must have a constant value." 它说:“表达式必须具有恒定值。” Apparently it works for other people to use const in these situations. 显然 ,在这些情况下其他人可以使用const But mine might work differently because my variable is defined by a function. 但是我的工作方式可能有所不同,因为我的变量是由函数定义的。 Here is that function: 这是该函数:

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;
}

I have tried following other suggestions and making my code follow this format: 我尝试遵循其他建议,并使我的代码遵循以下格式:
(Replace lines 2 & 3 of the first code block with this.) (以此替换第一个代码块的第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
}

But then that causes an error on "data" in line 4 of the first codeblock. 但这会导致第一个代码块第4行中的“数据”出现错误。 The error is Argument of type "float**" is incompatible with parameter of type "float (*)[5]" . 错误是Argument of type "float**" is incompatible with parameter of type "float (*)[5]" Here is the first line of the relevant function: 这是相关功能的第一行:

void readIntoArray(float data[][MAXCOLUMNS], int arrayX, int arrayY, string filename)

MAXCOLUMNS is #define d as 5. MAXCOLUMNS#define d为5。

How do I pass the 2D array into the function without creating an error? 如何在不产生错误的情况下将2D数组传递给函数?
I am not the most experienced in c++, so I might be missing something obvious. 我不是C ++经验最丰富的人,因此我可能会缺少一些明显的东西。

There is a difference between: 之间有一个区别:

const int rows = numlines("health.txt");

and

const int rows = 20;

In both cases the value of the variable cannot modified once it is initialzed. 在这两种情况下,变量的值一经初始化就无法修改。 The difference is that in the first case, the value won't be known until run time while in the second case, the value is known at compile time. 区别在于,在第一种情况下,直到运行时才知道该值,而在第二种情况下,在编译时就知道了该值。

In C++, an array can be declared using a variable only if its value is known at compile time. 在C ++中,只有在编译时知道其值的情况下,才可以使用变量声明数组。

That explains why you cannot use: 这就解释了为什么您不能使用:

 const int rows = numlines("health.txt");
 float data[rows][5] = {0};

but you can use: 但您可以使用:

 const int rows = 20;
 float data[rows][5] = {0};

You can easily get around that issue by using an std::vector of std::vector s. 您可以使用std::vectorstd::vector轻松解决该问题。

 const int rows = numlines("health.txt");
 std::vector<std::vector<float>> data(rows, std::vector<float>(5));

Since you know the size of the inner array, you can also you std::array . 由于您知道内部数组的大小,因此也可以使用std::array It will make the declaration a little simpler. 它将使声明更加简单。

 std::vector<std::array<float, 5>> data(rows);

In C++,you can use "std::vector< T >" to save your data as a variable size array. 在C ++中,可以使用“ std :: vector <T>”将数据保存为可变大小的数组。

Just learn how to use STL,it would simplify your works. 只要学习如何使用STL,它就能简化您的工作。

You can use alloca to implement the equivalent of a variable length array: 您可以使用alloca来实现等价于可变长度数组:

    float (*data)[5] = (float (*)[5]) _alloca(rows * 5 * sizeof(float));

This will allocate local (stack) space and set data to point to the first row (with 5 columns) of a matrix of floats. 这将分配局部(堆栈)空间并设置数据以指向浮点矩阵的第一行(5列)。 The 5 can be replaced with a constant. 5可以替换为常数。 You can then use data like a normal local matrix, data[ i ][ j ] ... . 然后,您可以使用像普通局部矩阵这样的数据data [i] [j] ...。 Depending on the compiler, the name may be alloca() instead of _alloca(), and the cast (float (*)[5]) may not be needed. 根据编译器的不同,名称可能是alloca()而不是_alloca(),并且可能不需要强制转换(float(*)[5])。

Since this is a local allocation, it's automatically freed when the function exits. 由于这是本地分配,因此在函数退出时会自动释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM