swap in template helper function

The function swap is used to exchange two values, and its definition is as follows:

Of course, what if what you want to exchange is a container? For example, if we want to exchange two vectors, obviously the above code cannot do anything. You may think of overloading a swap function to define your own swap logic. Of course it is possible, but do you have to customize it with so many containers? And we know that many containers have their own swap method. Let’s take a look: there are still many containers that have the swap function defined.

Let's take a look at swap in vector:

 Note our comment: to swap the elements of two vectors in constant time, the global std::swap function is specialized so std::swap(v1, v2) is fed to this function. If you don’t understand what this sentence means, it doesn’t matter, take a look at the following code:

We define a swap function in the std space. This swap function is not the swap function that comes with the container. It calls 

 The swap function that comes with the container allows you to call the standard swap method with two elements instead of the swap method that comes with the container. Obviously the two-parameter swap method is more in line with our intuition, and as long as your custom class After implementing the swap method like vector, you can also use std::swap to exchange your custom classes!

 

Guess you like

Origin blog.csdn.net/qq_55621259/article/details/130249206