如何使从函数返回的数字用于定义数组中的任何元素
How to make a number returned from a function be used for defining no of elements in an array?
我正在使用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;
,这也是更好的解决方案。
相关文章:
- C++编程从外部文本文件定义数组大小
- 如何在子类中重新定义数组大小?
- 有没有办法根据命令行参数定义数组大小?运行时与编译时实例化?
- 我可以使用常量定义数组的长度,那么为什么 int d[b] 不起作用呢?
- 表达式必须具有常数值,变量不能用作定义数组大小的常数
- 在类中定义数组的方法和字段
- (C++)我的自定义数组无法初始化(编译错误)
- 重写自定义数组类的运算符/开始/结束
- 如何在 C++ 中定义数组数组
- 您可以在类初始化器列表中定义数组大小吗?
- 通过Overloading Operator []访问自定义数组包装器中的元素
- 为自定义数组实现迭代器
- 递归定义数组中的数据对齐和排序
- 如何从类中返回自定义数组项目并操纵其属性?C
- 如何使用类 .h 文件中的静态常量来定义数组的长度
- 使用类定义数组创建C++类
- C++自定义数组容器动态大小
- C++中使用什么类型来定义数组大小
- 在源文件中定义数组,然后在其他源文件中使用它
- C 编程从外部输入文件定义数组大小