When to Choose Vector vs. List in the STL
According to Effective STL, the vector container should be the default choice for sequences. However, this recommendation requires further clarification.
Vector vs. List: Key Differences
To understand the distinction between vectors and lists, consider the following table:
Feature | Vector | List |
---|---|---|
Memory allocation | Contiguous | Non-contiguous |
Storage overhead | Pre-allocates space | Constant memory overhead |
Element space | No extra pointers | Extra space for node (pointers to next/previous) |
Memory reallocation | Can reallocate memory for entire vector | Never reallocates memory for entire list |
Insertion efficiency | O(1) at end, O(n) elsewhere | O(1) anywhere |
Erasure efficiency | O(1) at end, O(n) elsewhere | O(1) always |
Random access | Supported | Not supported |
Iterator validity | Invalidated after additions/removals | Remains valid after additions/removals |
Array access | Underlying array easily obtained | No underlying array available |
When List May Be Preferable
While vectors are generally more efficient, lists can be a better choice in specific scenarios:
The above is the detailed content of Vector vs. List in the STL: When Should You Choose Which?. For more information, please follow other related articles on the PHP Chinese website!