爲什麼普通算法模板被設計爲接受兩個迭代器而不是這些迭代器對?考慮下面這個例子:接受兩個迭代器的模板
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
template <typename Range, typename OutputIterator>
void copy2 (Range r, OutputIterator o) {
copy (r.first, r.second, o);
}
template <typename iter1, typename iter2>
pair<typename iter1, typename iter2> Range(iter1 start, iter2 end) {
return make_pair(start, end);
}
int main()
{
vector<int> myvector;
myvector.push_back(3);
myvector.push_back(2);
myvector.push_back(1);
// ordinary algorithm template accepts two iterators
copy(myvector.begin(),
myvector.end(),
ostream_iterator<int> (cout,"\n"));
// this template accepts iterator Range
copy2(Range(myvector.begin(),myvector.end()),
ostream_iterator<int> (cout,"\n"));
}
什麼是副本的原因()比COPY2()更好[比COPY2其他()調用冗長]
編輯:我砍倒COPY2的冗長( ),如DeadMG所建議的那樣。
把迭代器包裝成一對有什麼好處?我所看到的只是它需要更多的輸入和對類型的依賴。 –
copy2()的詳細程度不是一個足夠好的理由嗎? –
@Joe:這是真的,但可以用一點想象力輕鬆解決。 – Puppy