std::vector and contiguous memory of multidimensional arrays

The standard does require the memory of an std::vector to be contiguous. On the other hand, if you write something like:

std::vector<std::vector<double> > v;

the global memory (all of the v[i][j]) will not be contiguous. The usual way of creating 2D arrays is to use a single

std::vector<double> v;

and calculate the indexes, exactly as you suggest doing with float. (You can also create a second std::vector<float*> with the addresses if you want. I've always just recalculated the indexes, however.)


Elements of a Vector are gauranteed to be contiguous as per C++ standard.
Quotes from the standard are as follows:

From n2798 (draft of C++0x):

23.2.6 Class template vector [vector]

1 A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. 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().

C++03 standard (23.2.4.1):

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().

Also, see here what Herb Sutter's views on the same.