c++ expression must have a constant value

2020-04-08 14:58发布

I have this method:

void createSomething(Items &items)
{
    int arr[items.count]; // number of items
}

But it's throwing an error:

expression must have a constant value

I found just this solution:

int** arr= new int*[items.count];

so I'm asking is there a better way how do handle this?

标签: c++ arrays
2条回答
太酷不给撩
2楼-- · 2020-04-08 15:15

You can use a std::vector

void createSomething(Items &items)
{
    std::vector<int> arr(items.count); // number of items
}

The reason your first method won't work is that the size of an array must be know at compile time (without using compiler extensions), so you have to use dynamically sized arrays. You can use new to allocate the array yourself

void createSomething(Items &items)
{
    int* arr = new int[items.count]; // number of items

    // also remember to clean up your memory
    delete[] arr;
}

But it is safer and IMHO more helpful to use a std::vector.

查看更多
▲ chillily
3楼-- · 2020-04-08 15:38

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

查看更多
登录 后发表回答