Ferruccio Ferruccio - 1 year ago 73
C++ Question

Is it safe to assume that STL vector storage is always contiguous?

If you have an STL vector which has been resized, is it safe to take the address of element 0 and assume the rest of the vector will follow in memory?


vector<char> vc(100);
// do some stuff with vc
char* p = &vc[0];
// do stuff with *p

Answer Source

Yes, that is a valid assumption (*).

From the C++03 standard (

The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

(*) ... but watch out for the array being reallocated (invalidating any pointers and iterators) after adding elements to it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download