C++ vector with dynamic item size

前端 未结 9 2230
无人及你
无人及你 2021-01-14 16:54

the C++ STL vector has a lot of decent properties, but only works when the size of each item is known at run-time.

I would like to have a vector class that features

9条回答
  •  抹茶落季
    2021-01-14 17:12

    vector represent a contiguous array in memory. This is efficient, since it can use pointer arithmetics to directly access elements by index. But doing that imply all elements having the same size, and to know this size before building the vector.

    For your needs, either use a vector of pointers to elements, of a double linked list. vector of pointers is almost as fast as vector. It only needs one mode deference.

    If your integers and doubles are the same size (e.g. 64 bits), you could use an union to access each item either as an integer or as a double. But you'd need a way to know what each element is supposed to be.

提交回复
热议问题