按照http://www.cplusplus.com/reference/algorithm/swap/
中提到的,swap的原理应该是这样的:
template <class T> void swap ( T& a, T& b )
{
T c(a); a=b; b=c;
}
比如
a[] = {1, 2, 3};
b[] = {4, 5, 6};
swap(a, b)
就可以将两个数组进行交换。
但是按照我传统对C语言的理解,我本身自己写的函数如
void func(int *a){
//TODO
}
func(a);
传过去的是个数字首个内容的地址。如果交换指针的值的话,交换的也只是首个位置,无法更改后续位置。
而swap源码可以交换整个数组。而且,我并没有传整个数组的长度进去。甚至类似的,多维数组也可以交换。
那么他实现的机理是什么呢?
Questioner, the following is the implementation of swap. It uses a template implementation. When I pass an array to it, it can deduce the size of the array, such as int a[] ={1,2,3, 4}, when a is passed to this function, _Size is deduced to be 4.
The function of iter_swap is to exchange the values pointed to by two iterators,
The content in the swap above is as follows:
You will understand after compiling this code. If you don’t understand, come back and ask above
You don’t understand the concept of c++ references.
References and pointers are similar, but different.
The dereference operation will get the original object itself, unlike the pointer, which can only get the contents of the memory pointed to by the pointer
so,
It is equivalent to passing the entire array to the function. This is the advantage of references. Otherwise, why would C++ have the concept of references?