开发者

Dynamic size of array in c++?

I am confused. I don't know what containers should I use. I tell you what I need first. Basically I need a container that can stored X number of Object (and the number of objects is unknown, it could be 1 - 50k).

I read a lot, over here array vs list its says: array need to be resized if the number of objects is unknown (I am not sure how to resize an array in C++), and it also stated that if using a linked list, if you want to search certain item, it will loop through (itera开发者_运维百科te) from first to end (or vice versa) while an array can specify "array object at index".

Then I went for an other solution, map, vector, etc. Like this one: array vs vector. Some responder says never use array.

I am new to C++, I only used array, vector, list and map before. Now, for my case, what kind of container you will recommend me to use? Let me rephrase my requirements:

  • Need to be a container
  • The number of objects stored is unknown but is huge (1 - 40k maybe)
  • I need to loop through the containers to find specific object


std::vector is what you need.
You have to consider 2 things when selecting a stl container.

  1. Data you want to store
  2. Operations you want to perform on the stored data

There wasa good diagram in a question here on SO, which depitcs this, I cannot find the link to it but I had it saved long time ago, here it is:

Dynamic size of array in c++?


You cannot resize an array in C++, not sure where you got that one from. The container you need is std::vector.


The general rule is: use std::vector until it doesn't work, then shift to something that does. There are all sorts of theoretical rules about which one is better, depending on the operations, but I've regularly found that std::vector outperforms the others, even when the most frequent operations are things where std::vector is supposedly worse. Locality seems more important than most of the theoretical considerations on a modern machine.

The one reason you might shift from std::vector is because of iterator validity. Inserting into an std::vector may invalidate iterators; inserting into a std::list never.


Do you need to loop through the container, or you have a key or ID for your objects?

If you have a key or ID - you can use map to be able to quickly access the object by it, if the id is the simple index - then you can use vector.

Otherwise you can iterate through any container (they all have iterators) but list would be the best if you want to be memory efficient, and vector if you want to be performance oriented.


You can use vector. But if you need to find objects in the container, then consider using set, multiset or map.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜