如何实现C ++ std :: vector? [英] How is C++ std::vector implemented?
问题描述
我一直使用 std :: vector
很多,最近我问自己这个问题: std :: vector
已实现?
我有两个选择:
使API感觉像随机访问(即重载 operator []
)。
2)使用 new
,例如 Foo * temp = new Foo [20]
:我相信他们做这样的事情,但后来又提出了一个问题。他们总是分配一个最大( uint32_t
)存储以提供随机访问吗?
或者还有其他我应该注意的事情?
这是不可能实现 en.cppreference.com/w/cpp/container/vector> std :: vector< T>
,因为标准保证元素该列表将被保存在连续的内存中。
I have been using std::vector
a lot, and recently I asked myself this question: "How is std::vector
implemented?"
I had two alternatives:
1) Linked list, and then making the API feel like random access (i.e. overloading operator[]
).
2) Using new
, e.g. Foo* temp = new Foo[20]
: I believe they do something like this, but then it raises one more question. Do they always allocate a maximum (uint32_t
) storage to give random access? (This is inefficient in terms of memory.)
Or is there something else that I should be aware of?
It's implemented by using an underlying array.
It's not possible to implement a std::vector<T>
with a linked list because the standard guarantees the elements in the list will be held in contiguous memory.
这篇关于如何实现C ++ std :: vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!