swap原型:
header | // moved from <algorithm> to <utility> in C++11
|
---|---|
non-array (1) | template <class T> void swap (T& a, T& b)
noexcept (is_nothrow_move_constructible<T>::value && is_nothrow_move_assignable<T>::value);
|
array (2) | template <class T, size_t N> void swap(T (&a)[N], T (&b)[N])
noexcept (noexcept(swap(*a,*b))); |
行为类似于:
template <class T> void swap (T& a, T& b) { T c(std::move(a)); a=std::move(b); b=std::move(c); } template <class T, size_t N> void swap (T (&a)[N], T (&b)[N]) { for (size_t i = 0; i<N; ++i) swap (a[i],b[i]); }一个简单的例子:
#include <iostream> #include <algorithm> #include <vector> using namespace std; void mswap() { vector<int> vi{1,8,5,19,22,5,4}; vector<int> v2{1,45,88,33,15,0,-8}; cout<<"at first:"<<endl; cout<<"vi="; for(int i:vi) cout<<i<<" "; cout<<endl; cout<<"v2="; for(int i:v2) cout<<i<<" "; cout<<endl; swap(vi,v2); cout<<endl<<"after swap(vi,v2)"<<endl; cout<<"vi="; for(int i:vi) cout<<i<<" "; cout<<endl; cout<<"v2="; for(int i:v2) cout<<i<<" "; cout<<endl; }运行结果:
template <class ForwardIterator1, class ForwardIterator2> ForwardIterator2 swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2);
第二个范围从first2开始。
其行为类似于:
template<class ForwardIterator1, class ForwardIterator2> ForwardIterator2 swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2) { while (first1!=last1) { swap (*first1, *first2); ++first1; ++first2; } return first2; }一个简单的例子:
#include <iostream> #include <algorithm> #include <vector> using namespace std; void mswapranges() { vector<int> vi{1,8,5,19,22,5,4}; vector<int> v2{1,45,88,33,15,0,-8}; cout<<"at first:"<<endl; cout<<"vi="; for(int i:vi) cout<<i<<" "; cout<<endl; cout<<"v2="; for(int i:v2) cout<<i<<" "; cout<<endl; swap_ranges(vi.begin(),vi.end(),v2.begin()); cout<<endl<<"after swap_range(vi.begin(),vi.end(),v2.begin())"<<endl; cout<<"vi="; for(int i:vi) cout<<i<<" "; cout<<endl; cout<<"v2="; for(int i:v2) cout<<i<<" "; cout<<endl; }
——————————————————————————————————————————————————————————————————
//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。
转载请注明出处:http://blog.csdn.net/qq844352155
author:天下无双
Email:[email protected]
2014-9-26
于GDUT
——————————————————————————————————————————————————