关于 C++ stl容器交换函数
最近了解到所有的stl容器都有swap功能: ie
c1.swap(c2);
将导致底层对象 c1 被分配给 c2,反之亦然。 我问我的教授,如果 c1 和 c2 是参考文献,是否也是如此。 他说遵循同样的机制。
我想知道这是怎么发生的,因为 C++ 引用无法重置。
I recently learned that all stl containers have swap function:
i.e.
c1.swap(c2);
will lead to object underlying c1 being assigned to c2 and vice versa.
I asked my professor if same is true in case of c1 and c2 being references.
he said same mechanism is followed.
I wonder how it happens since c++ references cannot be reseted.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
引用是别名。如果您有两个引用,调用 swap 将交换它们所引用的内容,而不是引用本身。
交换的不是变量,而是使它们在逻辑上独立的因素。如果一个容器仅包含一个指针,如果您将该指针与另一个容器的指针交换,那么您就有效交换了容器。变量本身仍然存在。
具体例子:
References are aliases. If you have two references, calling swap will swap what they are referring to, not the references themselves.
And it's not the variables that get swapped, it's what make them logically independent that gets swapped. If a container only consists of a pointer, if you swap that pointer with the pointer of another container, you've effectively swapped the containers. The variables themselves remain.
Concrete example:
正在交换的是容器的内容,即
c1
的元素被移动到c2
,反之亦然。玩具实现可能如下所示:It's the content of the containers that's being swapped, i.e. the elements of
c1
are moved toc2
and vice versa. A toy implementation could look something like this: