Junior — Middle
How is storage of elements implemented in the std::vector container in C++?
sobes.tech AI
Answer from AI
In C++, the std::vector container implements a dynamic array that stores elements in a contiguous block of memory. When adding elements, if the current allocated buffer is full, a new, larger memory block is allocated, existing elements are copied to the new buffer, and the old buffer is freed.
This provides fast access to elements by index (operator []), since the memory is contiguous, but inserting or deleting elements in the middle of the vector can be costly due to the need to shift elements.
Example:
std::vector<int> v;
v.push_back(10); // adds an element to the end
int x = v[0]; // fast access to the first element
Thus, std::vector stores elements in a dynamically resizable array with contiguous memory.