Built in arrays
& std::array
always require a constant integer to determine their size. Of course in case of dynamic arrays
(the one created with new
keyword) can use a non-constant integer as you have shown.
However std::vector
(which of course internally a dynamic array only) uses a is the best solution when it comes to array-type applications
. It's not only because it can be given a non-constant integer as size but also it can grown as well as dynamically quite effectively. Plus std::vector
has many fancy functions to help you in your job.
In your question you have to simply replace int arr[items.count];
with :-
std::vector<int> arr(items.count); // You need to mention the type
// because std::vector is a class template, hence here 'int' is mentioned
Once you start with std::vector
, you would find yourself preferring it in 99% cases over normal arrays because of it's flexibility with arrays. First of all you needn't bother about deleting it. The vector will take care of it. Moreover functions like push_back
, insert
, emplace_back
, emplace
, erase
, etc help you make effective insertions & deletions to it which means you don't have to write these functions manually.
For more reference refer to this