The following is the definition of copy, according to http://www.sgi.com/tech/stl/copy.html.
template<class InputIterator, class OutputIterator>
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
while (first != last) *result++ = *first++;
return result;
}
I wrote the following code.
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());
Why does the call to copy above generate a runtime error but not a compile error? I’m assuming it has to do with the fact that the vector is empty, v.begin() == v.end(). But why?
Also, I fixed the code by changing it to the following.
copy(s.begin(), s.end(), back_inserter(v));
Function back_inserter returns an iterator of type back_insert_iterator>. Why does this work? What is it doing?
It fails because you’re not respecting the third precondition listed on this same site:
An empty vector is smaller than a set of 3 elements, so you cannot perform the copy operation (which really should be called an “overwrite” operation). This information is not known at compile-time and therefore there is no compile-time failure. Keep in mind that while vectors and most other C++ STL collections are expandable at runtime, they cannot be expanded through their regular iterators operations (which mostly serve the purpose of enumerating items and specifying ranges).
The
back_inserterfunction returns a special iterator that will insert elements to end of the collection. This iterator is an output iterator, and has very little to do with the iterators you can obtain through thebegin()andend()methods of the vector. You cannot read from an output iterator.