繁体   English   中英

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 arraysstd::array总是需要一个常量整数来确定它们的大小。 当然,在dynamic arrays情况下(使用new关键字创建的dynamic arrays )可以使用非常量整数,如您所示。

然而,当涉及到array-type applications时, std::vector (当然它内部只是一个动态数组)使用 a 是最好的解决方案。 这不仅是因为它可以被赋予一个非常量的整数作为大小,而且它还可以非常有效地动态增长。 另外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_backinsertemplace_backemplaceerase等帮助您进行有效的插入和删除它,这意味着你不必手动编写这些功能。

有关更多参考,请参阅

暂无
暂无

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

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