Regarding C ++ container change function stl

I recently found out that all stl containers have a swap function: i.e.

c1.swap(c2); 

will cause the object underlying c1 to be assigned to c2 and vice versa. I asked my professor if this is true if c1 and c2 are links. he said that the same mechanism was being followed.

I wonder how this happens, since C ++ links cannot be reset.

+4
source share
2 answers

Links are aliases. If you have two links, a swap call will replace what they reference, not the links themselves.

 C& r1 = c1; // r1 references c1 C& r2 = c2; // r2 references c2 r1.swap(r2); // same as c1.swap(c2) 

And these are not variables that change places, which makes them logically independent, which change places. If the container consists only of a pointer, if you swap that pointer with the pointer of another container, you are actually swapping the containers. The variables themselves remain.


Specific 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 
+4
source

The contents of containers that are swapped, i.e. elements c1 move to c2 and vice versa. A toy implementation might 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; }; 
+1
source

Source: https://habr.com/ru/post/1305733/


All Articles