lucmobz
lucmobz

Reputation: 483

Is a vector of arrays contiguous?

If I create

std::vector<std::array<double, 2>> points;
std::vector<double> points2;

I know that points2 will be a contiguous chunk of memory holding doubles in the heap. I think that points will be a contiguous chunk of memory of double* to the stack? But will those array be contiguous in the stack? Let's say that I am storing pairs of doubles to represents some points.

points2 is in memory like this: [x0 y0 x1 y1 x2 y2 ...] What about points? What is the best way to store pair of doubles in this case? Thanks for any tip.

Upvotes: 4

Views: 696

Answers (2)

Daniel Langr
Daniel Langr

Reputation: 23497

Is a vector of arrays contiguous?

No, it is not. std::array may contain padding or even additional members at the end. More details, e.g., here:


But I believe this is very unlikely to happen and you can simply check such situations by comparing 2 * sizeof(double) with sizeof(std::array<double, 2>).

Upvotes: 2

Bill Lynch
Bill Lynch

Reputation: 81926

Assuming that sizeof(std::array<double, 2>) is an integer multiple of alignof(std::array<double, 2>), then they should be stored contiguously with no padding.

And it's pretty likely that this will always be the case.

Upvotes: -1

Related Questions