天天看點

STL_算法_交換(swap_ranges)C++ Primer 學習中。。。

C++ Primer 學習中。。。

簡單記錄下我的學習過程 (代碼為主)

所有容器适用

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
**/