c++中std::swap使用方法

c++中std::swap使用方法

1.std::swap的源码:

template<typename _Tp>
    inline void
    swap(_Tp& __a, _Tp& __b)
#if __cplusplus >= 201103L
    noexcept(__and_<is_nothrow_move_constructible<_Tp>,
                is_nothrow_move_assignable<_Tp>>::value)
#endif
    {
      // concept requirements
      __glibcxx_function_requires(_SGIAssignableConcept<_Tp>)

      _Tp __tmp = _GLIBCXX_MOVE(__a);
      __a = _GLIBCXX_MOVE(__b);
      __b = _GLIBCXX_MOVE(__tmp);
    }

其中_GLIBCXX_MOVE() 是一个宏定义#define _GLIBCXX_MOVE(__val) std::move(__val) ,可以看出swap就是通过引用来交换a,b的值。

2.自定义swap()函数:

template<typename T>
void swap(T &a,T &b) noexcept
{
    T temp = std::move(a);
    a = std::move(b);
    b = std::move(temp);
}

3.测试std::swap()和自定义swap()函数

完整代码:

#include <iostream>
using namespace std;
template<typename T>
void swap(T &a,T &b) noexcept
{
    T temp = std::move(a);//使用了std::move函数
    a = std::move(b);
    b = std::move(temp);
}

void print_range01(int lhs,int rhs)
{
    if(lhs>rhs)
    {
        std::swap(lhs,rhs);
    }
    for(int i=lhs;i !=rhs;++i)
    {
        cout<<i<<" ";
    }
    cout<<endl;
}
void print_range02(int lhs,int rhs)
{
    if(lhs>rhs)
    {
        ::swap(lhs,rhs);//使用::表示是本文件定义的swap函数,避免与std::swap发生歧义
    }
    for(int i=lhs;i !=rhs;++i)
    {
        cout<<i<<" ";
    }
    cout<<endl;
}
void test01()
{
    int lhs=0,rhs=0;
    cin>>lhs>>rhs;
    print_range01(lhs,rhs);
}
void test02()
{
    int lhs=0,rhs=0;
    cin>>lhs>>rhs;
    print_range01(lhs,rhs);
}
int main()
{
    ::test01();//使用::表示是本文件定义的函数
    ::test02();
    return 0;
}

运行结果图:
这里写图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值