std::vector and contiguous memory of multidimensional arrays

user787267 picture user787267 · Jun 24, 2011 · Viewed 7.7k times · Source

I know that the standard does not force std::vector to allocate contiguous memory blocks, but all implementations obey this nevertheless.

Suppose I wish to create a vector of a multidimensional, static array. Consider 2 dimensions for simplicity, and a vector of length N. That is I wish to create a vector with N elements of, say, int[5].

Can I be certain that all N*5 integers are now contiguous in memory? So that I in principle could access all of the integers simply by knowing the address of the first element? Is this implementation dependent?

For reference the way I currently create a 2D array in a contiguous memory block is by first making a (dynamic) array of float* of length N, allocating all N*5 floats in one array and then copying the address of every 5th element into the first array of float*.

Answer

James Kanze picture James Kanze · Jun 24, 2011

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