I read that std::vector
should be contiguous. My understanding is, that its elements should be stored together, not spread out across the memory. I have simply acce
So what does it exactly mean, that std::vector is a contiguous container and why do its elements move? Does it maybe store them together, but moves them all together, when more space is needed?
That's exactly how it works and why appending elements does indeed invalidate all iterators as well as memory locations when a reallocation takes place¹. This is not only valid since C++17, it has been the case ever since.
There are a couple of benefits from this approach:
data()
method can be used to pass the underlying raw memory to APIs that work with raw pointers.push_back
, reserve
or resize
boil down to constant time, as the geometric growth amortizes over time (each time push_back
is called the capacity is doubled in libc++ and libstdc++, and approx. growths by a factor of 1.5 in MSVC).These implications can be considered the downside of such a memory layout:
push_front
(as std::list
or std::deque
provide) aren't provided (insert(vec.begin(), element)
works, but is possibly expensive¹), as well as efficient merging/splicing of multiple vector instances.¹ Thanks to @FrançoisAndrieux for pointing that out.