[英]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
關鍵字創建的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_back
, insert
, emplace_back
, emplace
, erase
等幫助您進行有效的插入和刪除它,這意味着你不必手動編寫這些功能。
有關更多參考,請參閱此
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.