ProgrammingBackend Developer

What are the differences between std::vector and std::list in C++? In which cases is it better to use each container, and what can go wrong with the wrong choice?

Pass interviews with Hintsage AI assistant

Answer

std::vector and std::list are different STL containers with distinct implementations and behaviors.

  • std::vector implements a dynamic array, with elements stored contiguously in memory. Fast access by index (O(1)), quick addition to the end (amortized O(1)), expensive insertions and deletions in the middle (O(n)), as elements must be shifted.
  • std::list is a doubly linked list. Slow random access (O(n)), fast insertions and deletions at any position in the list (O(1)), more memory overhead (two pointers per element) and frequent allocations/deallocations.

When to choose:

  • Use std::vector almost always, unless frequent insertions/deletions in the middle are needed.
  • std::list is justified only when insertions/deletions at any position are necessary with large data volumes, when moving elements in a vector is too costly.
  • For small collections, even when insertion in the middle is needed, std::vector is often faster due to data locality.

Example:

std::vector<int> v; v.push_back(1); v[0] = 2; // fast access by index std::list<int> l; l.push_back(1); // l[0] = 2; // Error: std::list does not have index access!

Trick Question

"Why is std::list rarely used in modern C++ projects despite the theoretical advantage of frequent insertions in the middle of the collection?"

Answer: Because in practice, due to numerous small allocations, loss of data locality (cache-friendly), bulkiness of the structure, and poor support for some operations (std::list is inefficient even for large lists due to time lost on allocation and deallocation, and slowdowns from cache misses often overshadow asymptotic gains). Additionally, modern processors are very sensitive to cache locality, so even with large data volumes, std::vector is often faster in real-world conditions.

Examples of real errors due to ignorance of the nuances of the topic


Story

In real-time systems for storing event queues, std::list was chosen for frequent deletions from arbitrary positions. As a result, the system became 10 times slower due to frequent heap accesses and poor data localization in memory.


Story

In a graphics processor, neighbor arrays were stored as std::list for insertions. This led to a dramatic increase in memory usage and degradation of L1/L2 caches, while there was no real gain in speed.


Story

In a report-building service, each report was collected from Linked List objects. During stress tests, the service started to "lag", and profiling showed bottlenecks in allocation costs when working with lists. They switched to vector — the result improved dramatically.