C ++数组的大小动态 [英] c++ dynamic size of the array
问题描述
我有一个小问题,一维数组在C ++中。我有一个功能线这样的:
I have got a small problem with 1D array in c++. I have got a function line this:
void func(int (&array)[???])
{
// some math here;
"for" loop {
array[i] = something;
}
}
我的地方调用的函数在code,和之前我做数学,我无法知道数组的维度。阵列转到函数作为参考!因为我需要在主体()函数。我该如何分配数组这样?所以数组?维度去功能作为参考,然后我不得不把维和写入一些值。
I call the functions somewhere in the code, and before I made math I'm not able to know dimension of the array. The array goes to the function as a reference!, because I need it in the main() function. How I can allocate array like this?, so array with ?? dimension goes to the function as reference then I have to put the dimension and write to it some values.
推荐答案
使用指针,而不是一个参考:
Use a pointer, not a reference:
void func(int *a, int N);
或者,更方便,使用一个向量:
Or, easier, use a vector:
void func(std::vector<int> &a);
向量可以通过简单地说,被分配
Vectors can be allocated by simply saying
std::vector<int> a(10);
可以通过检索元素的数量 a.size()
。
这篇关于C ++数组的大小动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!