Nothing (apart from efficiency concerns) stops a programmer from making an array a given minimum size and resizing it as need be by copying elements, correct? |
Emphasised for importance.
Increasing the size of a vector/array can be computationally expensive. It requires a large chunk of contiguous memory be allocated (in addition to to the original buffer).
For example if you're increasing from 100 bytes to 200 bytes in size, the computer actually needs
300 byte of memory available in order to increase the buffer size.
Then after the allocation, the entire array has to be copied to the new buffer. This can be expensive if it's done repeatedly. Even worse if the buffer size is substantailly large.
So don't vectors (or even properly managed arrays) give all the same benefits as a linked list without sacrificing random access efficiency? |
Functionally you can do just about anything with a vector that you can do with a list... yes. But the difference is HOW they do it.
Lists can have elements easily inserted/removed anywhere, including at the front. Vectors cannot. Try to insert an element at the front of a vector and you probably have to reallocate/copy the entire array.
EDIT:
Here's a practial example. Say you have a game and you want to keep track of all enemies that are on screen. Some enemies fire bullets which you treat as normal enemies. When an enemy dies, it is removed from the group.
A list is more suitable here because:
- you don't need random access. Any operations you do to an enemy you'll probably be doing to the entire enemy group. Collision detection, for example... you'd have to check against every enemy to see if they collided. AI logic, etc. It all would be done on the group as a whole. Random access has no real value.
- the constant additions of new enemies (in the form of spawning, or bullets, or whathaveyou) might cause several reallocations/copies in a vector. But is no problem for a list.
- the constant removal of arbitrary enemies (upon their death) would require
tons of object copying. If you're using a vector, everytime an enemy that isn't immediately at the end of the vector dies... all the enemies after it would have to be "shifted down" to fill the gap.
So yeah... if you need random access, you probably don't want a list. If you will be arbitrarily inserting/removing elements, you probably don't want a vector.
Different tools for different jobs.