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;
}
运行结果图: