Dynamic size of array in c++?

2019-03-06 04:44发布

问题:

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 (iterate) 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

回答1:

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:



回答2:

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



回答3:

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.



回答4:

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.



回答5:

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