STL 容器插入元素 [英] STL container insert element

查看:42
本文介绍了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.

推荐答案

分配器是一个模板参数.看看定义这里:

The allocator is a template parameter. Look at the definition here:

template < class Key, class Compare = less<Key>,
           class Allocator = allocator<Key> > class set;

如果您不指定自己的分配器,它将采用默认分配器(可能只是一个 new).

If you don't specify allocator of your own, it will take the default allocator (which would probably be just a new).

您可以在具有公共复制构造函数、析构函数和赋值运算符的类上使用 STL 容器.请参阅此处:

You can use STL containors on classes with public copy constructors, destructors and assignment operators. See here:

插入到 STL 容器中的元素可以是任何对象类型提供公共复制构造函数、公共析构函数和公共赋值运算符.析构函数可能不会抛出异常.此外,诸如 set 和 map 之类的关联容器必须具有定义了公共比较运算符,即 operator<;默认情况下.容器上的某些操作可能还需要公共默认值构造函数和公共等价运算符.

Elements inserted into an STL container can be of any object type that supplies a public copy constructor, a public destructor, and a public assignment operator. The destructor may not throw an exception. Furthermore, associative containers such as set and map must have a public comparison operator defined, which is operator< by default. Some operations on containers might also require a public default constructor and a public equivalence operator.

所以基本上复制是通过使用您在类中实现的上述公共成员函数来完成的.

So basically the copy is done by using the above public member functions that you implement in your classes.

这篇关于STL 容器插入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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