變異算法(Mutating algorithms)是一組能修改容器元素資料的模板函式,可進行序列的複製、變換等操作。第一個要認識的就是元素複製演算法 copy。
它主要用於容器之間的元素拷貝:把迭代器區間 [first, last) 的元素複製到由 result 指定的 [result, result+(last-first)) 區間中。
template<class InputIterator, class OutputIterator>
OutputIterator copy(
InputIterator _First,
InputIterator _Last,
OutputIterator _DestBeg
);
#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); // 必須先配置空間,否則程式會崩
// 用法一:把陣列七個元素複製到 myvector
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;
}
初學者最常犯的一個錯誤就是漏掉 myvector.resize(7)。copy 只負責搬資料,不會幫你配置空間,目標容器沒有足夠容量時程式就會崩掉。另外用法二說明了 copy 也支援同容器內的搬移,只要區間重疊方式在 copy 的語意允許範圍內即可。
#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 真正的威力所在:搭配 back_insert_iterator 就不需要事先 resize,元素會邊讀邊長;搭配 ostream_iterator 則一行取代整個輸出迴圈。把迭代器當成「資料的插槽」,copy 就只是一個把資料從一組插槽搬到另一組插槽的通用工具。