如何实现C ++ std :: vector? [英] How is C++ std::vector implemented?

查看:130
本文介绍了如何实现C ++ std :: vector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆