简体   繁体   English

关于C ++ stl容器交换功能

[英]regarding C++ stl container swap function

I recently learned that all stl containers have swap function: ie 我最近了解到所有stl容器都有交换功能:即

c1.swap(c2);  

will lead to object underlying c1 being assigned to c2 and vice versa. 将导致对象底层c1被分配给c2,反之亦然。 I asked my professor if same is true in case of c1 and c2 being references. 我问过我的教授,如果c1和c2是引用,情况是否也是如此。 he said same mechanism is followed. 他说跟随同样的机制。

I wonder how it happens since c++ references cannot be reseted. 我想知道它是如何发生的,因为c ++引用无法重置。

References are aliases. 引用是别名。 If you have two references, calling swap will swap what they are referring to, not the references themselves. 如果您有两个引用,则调用swap将交换它们所引用的内容,而不是引用本身。

C& r1 = c1; // r1 references c1
C& r2 = c2; // r2 references c2

r1.swap(r2); // same as c1.swap(c2)

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: 具体例子:

typedef std::vector<int> vec;

vec c1;
vec c2;

// fill em up

c1.swap(c2);
/*
A vector, internally, has a pointer to a chunk of memory (and some other stuff).
swap() is going to swap the internal pointer (and other stuff) with the other
container. They are logically swapped.
*/

vec& r1 = c1; // r1 is an alias for c1
vec& r2 = c2; // r2 is an alias for c2

r1.swap(r2); // same as c1.swap(c2). they are now unswapped

It's the content of the containers that's being swapped, ie the elements of c1 are moved to c2 and vice versa. 它是被交换的容器的内容,即c1的元素被移动到c2 ,反之亦然。 A toy implementation could look something like this: 玩具实现可能看起来像这样:

template <class T>
class vector {
    void swap(vector& other) {
        swap(other.m_elements, m_elements);
        swap(other.m_size, m_size):
    }
    T* m_elements;
    size_t m_size;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM