标签:
简单记录下我的学习过程 (代码为主)
所有容器适用
swap_ranges(b,e,b2) //优点: 可局部交换、可以在不同类型容器间交换
注意:下列两种方法也是交换算法
1、容器的swap()成员函数
2、赋值操作
/**------http://blog.csdn.net/u010579068------**/ #include<iostream> #include<cstdio> #include<string> #include<vector> #include<list> #include<deque> #include<algorithm> using namespace std; /***************************************** //所有容器适用 swap_ranges(b,e,b2) //优先可局部交换+可以在不同类型容器间交换 注意:下列两种方法也是交换算法 1、容器的swap()成员函数 2、赋值操作 *****************************************/ /**---------------------------------------------------------------------------------- ----------------------------------------------------------------------------------**/ /************************************************************************************* std::swap_ranges 所有排序容器适用 algorithm -------------------------------------------------------------------------------------- template < class ForwardIterator1, class ForwardIterator2 > ForwardIterator2 swap_ranges ( ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2 ); //eg: template<class ForwardIterator1, class ForwardIterator2> ForwardIterator2 swap_ranges ( ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2 ) { while (first1!=last1) swap(*first1++, *first2++); return first2; } *************************************************************************************/ int main() { vector<int> first (5,10); // first: 10 10 10 10 10 vector<int> second (7,33); // second: 33 33 33 33 33 5 vector<int>::iterator it; swap_ranges(first.begin()+1, first.end()-1, second.begin()); // print out results of swap: cout << "first contains:"; for (it=first.begin(); it!=first.end(); ++it) cout << " " << *it; cout << "\nsecond contains:"; for (it=second.begin(); it!=second.end(); ++it) cout << " " << *it; cout << endl; cout << endl; /**-------------------------------------------------------------------**/ //swap_ranges是有返回值的,返回的是迭代器,指向第二个容器的第一个没有交换的位置 int a[]={1,2,3,4,5,6,7}; int b[]={9,10,11,12}; vector<int> third (a,a+7); deque<int> fourth(b,b+4); deque<int>::iterator iter; auto riter=swap_ranges(third.begin()+2, third.end()-3, fourth.rbegin()+1); cout << "third contains:"; for (it=third.begin(); it!=third.end(); ++it) cout << " " << *it; cout << "\nfourth contains:"; for (iter=fourth.begin(); iter!=fourth.end(); ++iter) cout << " " << *iter; cout << endl; cout<<"第一个没有交换的元素: "<<*riter<<endl; return 0; } /******* Output: first contains: 10 33 33 33 10 second contains: 10 10 10 33 33 33 33 third contains: 1 2 11 10 5 6 7 fourth contains: 9 4 3 12 第一个没有交换的元素: 9 **/
标签:
原文地址:http://blog.csdn.net/u010579068/article/details/50531575