What is the most efficient way to initialize a 3D vector?

后端 未结 5 1424
长情又很酷
长情又很酷 2021-02-03 11:23

I have a 3D string vector in C++:

vector>> some_vector

That I am trying is to find a fast method to all

5条回答
  •  眼角桃花
    2021-02-03 11:59

    When you initialize a vector of vectors in the first method, a temporary vector is allocated and then copied into the outer vector the required number of times. This means you have an extra allocation that is unnecessary and the new elements are initialized by copying their value from another data structure, which uses more memory accesses.

    Resizing the vectors as per the second method is more ugly but avoids the extra allocation. Furthermore the new elements are created by the default constructor and do not need to copy from other vectors. This will also be faster.

    If speed matters (and maybe it doesn't, premature optimization and all that), then you must use the second method (OR a single-block allocation as suggested by the other answers). I don't have faith that a compiler can simply "optimize" away the inefficiency of the first method.

提交回复
热议问题