swap原型:
std::swap
- C++98
- C++11
header | |
---|---|
non-array (1) | |
array (2) | |
交換兩個對象(也可以是兩個容器)的值。
行為類似于:
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;
}
運作結果:
swap_ranges原型:
std::swap_ranges
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
——————————————————————————————————————————————————