如何使从函数返回的数字用于定义数组中的任何元素

How to make a number returned from a function be used for defining no of elements in an array?

本文关键字:定义 数组 元素 任何 用于 数字 何使 函数 返回      更新时间:2023-10-16

我正在使用Opencv/c++。我用这个函数得到视频中的帧数int noOfFrames = cvGetCaptureProperty( capture, CV_CAP_PROP_FRAME_COUNT );

我还声明了一个数组int Entropy[noOfFrames];。但是由于变量noOfFrames是非const的,所以它给出了一个错误。

我甚至使用const_cast,但它仍然给出了一个错误。我想让数组的长度等于视频的帧数

我该怎么做??

不能用动态大小声明静态数组。你需要一个动态数组:

int* Entropy = new Entropy[noOfFrames];
// use here, same as array
delete[] Entropy;

但是使用vector更简单:

std::vector<int> Entropy(noOfFrames);
// use here, same as array and more
// no need to clean up, std::vector<int> cleans itself up

在c++中,您不能这样做,因为C风格数组的大小应该是编译时常数1

无论如何,你有一个更好的选择:使用std::vector

std::vector<int> Entropy(noOfFrames);

即使你有编译时常量,我也不建议你使用int arr[size],这是c风格的数组。相反,我建议您使用std::array<int,size> arr;,这也是更好的解决方案。