c++ - STL中swap,实现交换两个数组的功能的原理是什么?
ringa_lee
ringa_lee 2017-04-17 13:08:04
0
3
956

按照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源码可以交换整个数组。而且,我并没有传整个数组的长度进去。甚至类似的,多维数组也可以交换。
那么他实现的机理是什么呢?

ringa_lee
ringa_lee

ringa_lee

reply all(3)
Peter_Zhu

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.

template<class _Ty,size_t _Size> 
inlinevoid swap(_Ty (&_Left)[_Size], _Ty (&_Right)[_Size])
    {    
    if (&_Left != &_Right)
        {    
        _Ty *_First1 = _Left;
        _Ty *_Last1 = _First1 + _Size;
        _Ty *_First2 = _Right;
        for (; _First1 != _Last1; ++_First1, ++_First2)
            _STD iter_swap(_First1, _First2);
        }
    }

The function of iter_swap is to exchange the values ​​pointed to by two iterators,

template<class _FwdIt1,
    class _FwdIt2> inline
    void iter_swap(_FwdIt1 _Left, _FwdIt2 _Right)
    {    // swap *_Left and *_Right
    swap(*_Left, *_Right);
    }

The content in the swap above is as follows:

        tmp = *_Right;
        *_Right = *_Left;
        *_Left = tmp;
洪涛
int a[] = {1,2,3};
int b[] = {2,4,5,6};
std::swap(a, b);

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,

swap ( T& a, T& b )

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?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template