c++表达式必须有一个常数值
c++ expression must have a constant value
我有这个方法:
void createSomething(Items &items)
{
int arr[items.count]; // number of items
}
但是它抛出了一个错误:
expression must have a constant value
我找到了这个解决方案:
int** arr= new int*[items.count];
所以我在问有没有更好的方法来处理这个?
您可以使用std::vector
void createSomething(Items &items)
{
std::vector<int> arr(items.count); // number of items
}
你的第一个方法不起作用的原因是数组的大小必须在编译时知道(不使用编译器扩展),所以你必须使用动态大小的数组。您可以使用new
自己分配数组
void createSomething(Items &items)
{
int* arr = new int[items.count]; // number of items
// also remember to clean up your memory
delete[] arr;
}
但使用std::vector
更安全,更有帮助。
Built in arrays
&std::array
总是需要一个常量整数来确定它们的大小。当然,在dynamic arrays
(用new
关键字创建的)的情况下,可以使用非常量整数,如您所示。
然而,std::vector
(当然内部只是一个动态数组)使用a是array-type applications
的最佳解决方案。这不仅是因为它的大小可以是一个非常数整数,而且它还可以动态增长,非常有效。另外,std::vector
有许多奇特的功能来帮助你的工作。
在您的问题中,您必须简单地将int arr[items.count];
替换为:-
std::vector<int> arr(items.count); // You need to mention the type
// because std::vector is a class template, hence here 'int' is mentioned
一旦你开始使用std::vector
,你会发现在99%的情况下你更喜欢它而不是普通数组,因为它对数组的灵活性。首先,你不必费心删除它。向量会解决这个问题。此外,push_back
, insert
, emplace_back
, emplace
, erase
等功能可以帮助您进行有效的插入&删除它,这意味着您不必手动编写这些函数。
有关更多参考,请参阅
相关文章:
- 有一个打印语句的函数是一种糟糕的编程实践吗
- VSCode-有一个红色下划线,但程序构建和运行正确,并且出现配音错误
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 有没有可能有一个只有ADL才能找到的非好友功能
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 我的程序有一个保存配置文件的GUI,如何双击此配置文件以直接加载带有配置数据的GUI?
- 在学习数据结构之前对STL有一个了解是好的吗?
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 是否可以在C++中有一个"generic"模板参数,该参数可以是非类型模板参数或类型?
- 编译器错误:函数调用在常量表达式中必须有一个常量值
- C++std用一个常数值列出初始化,它是否会改变性能
- c++表达式必须有一个常数值
- 如何创建一个std::map的常数值,它仍然可以被[]操作符访问
- 错误28:表达式必须有一个常量值
- 有一个用于常微分方程(ODE)求解的c++库
- Constexpr函数必须有一个参数值
- 表达式在c++中必须有一个常数值错误
- 错误:表达式必须具有常数值.对于一个明显的常数值
- 在c++中表达式必须有一个常数值