How does a C++ std::container (vector) store its internals (element address, access by index)?

混江龙づ霸主 提交于 2019-12-06 07:37:23

A typical (though by no means mandatory) implementation of vector is to have three consecutive words:

struct TypicalVector
{
    T * start;
    T * end;
    T * capacity;
};

Element access is done via start[i] (which is why it's important to have the start pointer at the front, to avoid unnecessary offset computations), size is end - start, and capacity is capacity - start. Memory allocation obtains c * sizeof(T) bytes and sets start to the address of the allocated memory and capacity to start + c. Element construction increments end.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!