Sobes.tech
Junior — Middle

Can you explain the differences between std::vector and std::list containers in C++?

sobes.tech AI

Answer from AI

std::vector and std::list are containers from the C++ standard library, but they have different characteristics:

  • std::vector:

    • Stores elements in a contiguous block of memory.
    • Fast access by index (O(1)).
    • Adding elements to the end is usually fast (amortized O(1)), but inserting or deleting in the middle is slow (O(n)) because elements need to be shifted.
    • Better suited for cases where quick random access and appending at the end are important.
  • std::list:

    • Implemented as a doubly linked list.
    • No random access (need to iterate to reach an element).
    • Inserting and deleting elements anywhere in the list is fast (O(1)), if an iterator to the position is available.
    • Uses more memory due to storing pointers.

Example usage:

#include <vector>
#include <list>

std::vector<int> v = {1, 2, 3};
v.push_back(4); // quickly adds to the end

std::list<int> l = {1, 2, 3};
auto it = l.begin();
std::advance(it, 1);
l.insert(it, 10); // quickly inserts before the second element

The choice depends on the task: if fast access by index is needed — vector; if frequent insertions/deletions in the middle — list.