生活随笔
收集整理的這篇文章主要介紹了
stl 之 copy copy_backward
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
http://blog.csdn.net/jerryjbiao/article/details/7381498
元素復制算法copy
該算法主要用于容器之間元素的拷貝,即將迭代器區間[first,last)的元素復制到由復制目標result給定的區間[result,result+(last-first))中。下面我們來看看它的函數原型:
函數原形:
[cpp]?view plaincopy
template<class?InputIterator,?class?OutputIterator>?? ???OutputIterator?copy(?? ??????InputIterator?_First,??? ??????InputIterator?_Last,??? ??????OutputIterator?_DestBeg?? ???);??
參數
_First,?_Last
指出被復制的元素的區間范圍[ _First,_Last)._DestBeg?
指出復制到的目標區間起始位置
返回值
返回一個迭代器,指出已被復制元素區間的最后一個位置
程序示例:
首先我們來一個簡單的示例,定義一個簡單的整形數組myints,將其所有元素復制到容器myvector中,并將數組向左移動一位。
[cpp]?view plaincopy
? ? ? ? ? ? ? ? ? ? ? ? ?? ?? #include?<iostream>?? #include?<algorithm>?? #include?<vector>?? ?? using?namespace?std;?? ?? int?main?()??? {?? ????int?myints[]?=?{10,?20,?30,?40,?50,?60,?70};?? ????vector<int>?myvector;?? ????vector<int>::iterator?it;?? ?????? ????myvector.resize(7);????? ?????? ?????? ?????? ????copy?(?myints,?myints+7,?myvector.begin()?);?? ?????? ????cout?<<?"myvector?contains:?";?? ????for?(?it?=?myvector.begin();??it?!=?myvector.end();??++it?)?? ????{?? ????????cout?<<?"?"?<<?*it;?? ????}?? ????cout?<<?endl;?? ?? ?????? ?????? ????copy(myints?+?1,?myints?+?7,?myints);?? ?? ????cout?<<?"myints?contains:?";?? ????for?(?size_t?i?=?0;?i?<?7;?++i?)?? ????{?? ????????cout?<<?"?"?<<?myints[i];?? ????}?? ????cout?<<?endl;?? ?? ????return?0;?? }??
從上例中我們看出copy算法可以很簡單地將一個容器里面的元素復制至另一個目標容器中,上例中代碼特別要注意一點就是myvector.resize(7);這行代碼,在這里一定要先為vector分配空間,否則程序會崩,這是初學者經常犯的一個錯誤。其實copy函數最大的威力是結合標準輸入輸出迭代器的時候,我們通過下面這個示例就可以看出它的威力了。
[cpp]?view plaincopy
? ? ? ? ? ? ? ? ? ? ? ? ?? ?? #include?<iostream>?? #include?<algorithm>?? #include?<vector>?? #include?<iterator>?? #include?<string>?? ?? using?namespace?std;?? ?? int?main?()??? {?? ?????typedef?vector<int>?IntVector;?? ?????typedef?istream_iterator<int>?IstreamItr;?? ?????typedef?ostream_iterator<int>?OstreamItr;?? ?????typedef?back_insert_iterator<?IntVector?>?BackInsItr;?? ??? ?????IntVector?myvector;?? ?? ??????? ??????? ?????cout?<<?"Please?input?element:"?<<?endl;?? ?????copy(IstreamItr(cin),?IstreamItr(),?BackInsItr(myvector));?? ?? ??????? ?????cout?<<?"Output?:?"?<<?endl;?? ?????copy(myvector.begin(),?myvector.end(),?OstreamItr(cout,?"?"));??? ?????cout?<<?endl;?? ?? ????return?0;?? }??
copy_backward(first, last, result)
拷貝行為和copy類似,只是方向相反
對于區間[first, last) 內每一個元素,以逆方向復制到以result - 1 為起點,方向亦為逆行的區間。大體模擬就是
*(result - 1)= *(last - 1),?*(result - 2)= *(last - 2),?*(result - 3)= *(last - 3),..
返回的迭代器為result - (last-first)
當源區間和目標區間不重疊時,或者是兩個不同的 緩沖區,copy 和copy_backward最終的效果是類似的。
但是,如果區間有重疊,問題就出現了:
copy允許尾部和輸入區間重疊,
copy_backward允許頭部和輸入區間重疊
當不滿足上述條件的重疊時,這兩個函數不保證正確。
總結
以上是生活随笔為你收集整理的stl 之 copy copy_backward的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。