STL容器插入元素
我正在研究 std::set
代码。我看到 insert
签名为 _Pairib insert(const value_type& _Val)
。为什么输入参数是通过引用传递的?我知道 standardcContainers 将它们的元素复制到容器的内存中。有谁知道这是如何实现的?分配器在哪里介入?任何解释元素如何存储/插入的小代码/伪代码将不胜感激。我有兴趣了解副本是如何完成的。
I was looking into std::set
code. I see insert
signature as _Pairib insert(const value_type& _Val)
. Why is the input parameter passed by reference? I know that standardcContainers copy their elements into memory of the container. Does anybody know how this is achieved? Where do allocators enter the picture? Any small code/pseudocode which explains how the elements are stored/inserted would be appreciated. I am interested in understanding how the copy is done.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
分配器是一个模板参数。看这里的定义:
如果你没有指定自己的分配器,它将采用默认分配器(可能只是一个
new
)。您可以在具有公共复制构造函数、析构函数和赋值运算符的类上使用 STL 容器。请参阅此处:
因此基本上复制是通过使用您在类中实现的上述公共成员函数来完成的。
The allocator is a template parameter. Look at the definition here:
If you don't specify allocator of your own, it will take the default allocator (which would probably be just a
new
).You can use STL containors on classes with public copy constructors, destructors and assignment operators. See here:
So basically the copy is done by using the above public member functions that you implement in your classes.
如果按值获取,则需要两份副本:一份用于函数参数,另一份用于容器节点。
容器请求分配器分配并初始化私有节点类型,该类型通常包含元素类型以及其他信息,例如指向其他节点的指针。
私有节点类型将保存传递给
insert
的参数的副本。If it would be taken by value, then two copies will be needed: one for the function argument, and another one for the container node.
The container requests the allocator to allocate and initialize a private node type that usually contains the element type as well as other information such as pointers to other nodes.
The private node type would hold a copy of the argument passed to
insert
.