C++ textbooks, and threads, like these say that vector elements are physically contiguous in memory.
But when we do operations like v.push_back(3.14) I would assume the STL is using the new operator to get more memory to store the new element 3.14 just introduced into the vector.
Now say the vector of size 4 is stored in computer memory cells labelled 0x7, 0x8, 0x9, 0xA. If cell 0xB contains some other unrelated data, how will 3.14 go into this cell? Does that mean cell 0xB will be copied somewhere else, erased to make room for 3.14?
std::vectorfirst allocates a bigger buffer, then copies existing elements from the “old” buffer to the “new” buffer, then it deletes the “old buffer”, and finally adds the new element into the “new” buffer.Generally,
std::vectorimplementation grow their internal buffer by doubling the capacity each time it’s necessary to allocate a bigger buffer.As Chris mentioned, every time the buffer grows, all existing iterators are invalidated.