c++表达式必须有一个常数值



我有这个方法:

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等功能可以帮助您进行有效的插入&删除它,这意味着您不必手动编写这些函数。

有关更多参考,请参阅

最新更新