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

C++ 关于C++;stl容器交换功能,c++,stl,containers,C++,Stl,Containers,我最近了解到,所有stl容器都具有交换功能: i、 e 将导致c1下面的对象被分配给c2,反之亦然。 我问我的教授,如果c1和c2是参考文献,情况是否也是如此。 他说同样的机制也在遵循 我不知道它是怎么发生的,因为C++的引用不能重置。 正在交换的是容器的内容,即c1的元素被移动到c2,反之亦然。玩具的实现可以是这样的: template <class T> class vector { void swap(vector& other) { swap(

我最近了解到,所有stl容器都具有交换功能: i、 e

将导致c1下面的对象被分配给c2,反之亦然。 我问我的教授,如果c1和c2是参考文献,情况是否也是如此。 他说同样的机制也在遵循


我不知道它是怎么发生的,因为C++的引用不能重置。 正在交换的是容器的内容,即
c1
的元素被移动到
c2
,反之亦然。玩具的实现可以是这样的:

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;
};
模板
类向量{
无效交换(向量和其他){
交换(其他m_元素、m_元素);
交换(其他m_大小,m_大小):
}
T*m_元素;
大小;
};

引用是别名。如果有两个引用,调用swap将交换它们所引用的内容,而不是引用本身

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

r1.swap(r2); // same as c1.swap(c2)
交换的不是变量,而是使它们在逻辑上独立的因素。如果一个容器只包含一个指针,那么如果您将该指针与另一个容器的指针交换,那么您已经有效地交换了容器。变量本身仍然存在


具体例子:

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
typedef std::vector vec;
vec c1;
vec-c2;
//加满
c1.互换(c2);
/*
向量在内部有一个指向内存块(以及其他内容)的指针。
swap()将内部指针(和其他内容)与另一个指针交换
容器。它们在逻辑上交换。
*/
向量&r1=c1;//r1是c1的别名
vec&r2=c2;//r2是c2的别名
r1.交换(r2);//与c1相同。互换(c2)。它们现在没有开关

ok,那么如果c1指向一个say pair,那么pair对象中的指针现在就被更改了。@sm1:你指的是什么意思?让我编辑一下,给出一个具体的例子,这样我们可以澄清一些困惑。
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