以下是根據http://www.sgi.com/tech/stl/copy.html複製的定義。STL複製執行
template<class InputIterator, class OutputIterator>
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
while (first != last) *result++ = *first++;
return result;
}
我寫了下面的代碼。
vector<int> v;
set<int> s;
s.insert(7);
s.insert(11);
s.insert(27);
//copy elements from the set into the vector
copy(s.begin(), s.end(), v.begin());
爲什麼上面複製的調用會生成運行時錯誤而不是編譯錯誤?我假設它與向量爲空的事實有關,v.begin()== v.end()。但爲什麼?
此外,我通過將其更改爲以下來修復了該代碼。
copy(s.begin(), s.end(), back_inserter(v));
函數back_inserter返回類型爲back_insert_iterator>的迭代器。爲什麼這個工作?它在做什麼?