The following code compiles just fine, overwriting the values in v2 with those from v1:
std::vector<int> v1 = {1, 2, 3, 4, 5};
std::vector<int> v2 = {6, 7, 8, 9, 10};
std::copy(v1.begin(), v1.end(), v2.begin());
The third argument of std::copy is an OutputIterator. However, the Container requirements specify that a.begin(), where a is a Container object, should have a return type of iterator which is defined as:
any iterator category that meets the forward iterator requirements.
Forward iterator requirements do not include the requirements of output iterators, so is the example above undefined? I’m using the iterator as an output iterator even though there’s no obvious guarantee that it will be one.
I’m fairly certain the above code is valid, however, so my guess is that you can infer from the details about containers that the forward iterator returned by begin() will in fact also support the output iterator requirements. In that case, when does begin() not return an output iterator? Only when the container is const or are there other situations?
Forward iterators can conform the the specifications of an output iterator if they’re mutable, depending on the type of the sequence. It’s not explicitly spelled out (unlike the fact that they to input iterator requirements), but if we take a look at the requirements table
we can go and check if a given forward iterator conforms to them:
A mutable reference is assignable (unless you have a non-assignable type, obviously).
The first line in Table 109 is the same requirement as for output iterators, except that forward iterators don’t have the remark. The second line is more restrictive than for output iterators, since it specifies that a
referencemust be returned.Bottom line, if you have a mutable forward iterator into a sequence of copy-assignable types, you have a valid output iterator.
(Technically, a constant iterator into a sequence of types that have a
operator=(...) constand mutable members would also qualify, but let’s hope nobody does something like that.)