Vector storage in C++

前端 未结 5 534
轮回少年
轮回少年 2021-02-05 01:08

I wish to store a large vector of d-dimensional points (d fixed and small: <10).

If I define a Point as vector, I think a v

5条回答
  •  粉色の甜心
    2021-02-05 01:12

    If you define your Point as having contiguous data storage (e.g. struct Point { int a; int b; int c; } or using std::array), then std::vector will store the Points in contiguous memory locations, so your memory layout will be:

    p0.a, p0.b, p0.c, p1.a, p1.b, p1.c, ..., p(N-1).a, p(N-1).b, p(N-1).c
    

    On the other hand, if you define Point as a vector, then a vector has the layout of vector>, which is not contiguous, as vector stores pointers to dynamically allocated memory. So you have contiguity for single Points, but not for the whole structure.

    The first solution is much more efficient than the second (as modern CPUs love accessing contiguous memory locations).

提交回复
热议问题