开发者

How to make a global array with variable number of elements?

Is it posible to declare a global array of a struct, and add 开发者_开发百科elements dynamically to it?

Thanks.


If you want to dynamically add elements to something, you might consider using a list. You could create a global list, and dynamically add elements to it as needed. If you really need array type functionality, a vector might be more your speed. In this case, the STL is likely to provide what you need.

It's also good to note that globals aren't always a good idea. If you're using globals a lot, you may want to consider refactoring your code so they won't be necessary. Many people consider global variables to be a code smell.


Avoid using non-PODs as globals. However, you can do this:

std::vector<YourStruct>& global_list()
{
    static std::vector<YourStruct> v;
    return v;
}

This at least avoids global initialization order problems by enforcing a policy where access is initialization. Otherwise you'll very easily wander into undefined behavior land.

As for what variable-sized container to use, it's hard to tell without more contextual information. Do you need to be able to quickly search for elements in the list, for example? Will you be removing elements from the middle of the list frequently? Do you need random-access, or is sequential iteration fine? Etc. etc.


See std::vector.

Any time you're tempted to use an array, you'd probably do better to use a vector, list, or one of the many other STL containers.


No, not directly. But you may use a STL or self-made vector.


You can use a STL container. Alternatively you can declare of your type and allocate/deallocate memory by yourself. But you should not use the 2nd way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜