While looking at std::copy_if details at here, the 3rd argument is an OutputIterator.
template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator copy_if (InputIterator first, InputIterator last,
OutputIterator result, UnaryPredicate pred);
I have below code which is using std::back_inserter as the 3rd argument. When i look at std::back_inserter details here , then it doesn’t mention it as an OutputIterator.
- Is
OutputIteratorany class OR just a way to indicate any Iterator which can output something? - Is
OutputIteratorrelated to ostream_iterator somehow? - Why its mentioned here that Incrementing the
std::ostream_iteratoris a no-op. What does it mean? Does it mean that we can’t do a ++ onstd::ostream_iterator?
int main()
{
std::vector<int> vec {1, 22, 3, 4, 5, 12, 14};
std::vector<int> rvec;
std::copy_if(std::begin(vec), std::end(vec), std::back_inserter(rvec), [](const int& x){ return (x % 2 == 0);})
}
>Solution :
OutputIterator here is an exposition-only name for the template parameter. It has no specific functionality.
The linked site unfortunately doesn’t specify which types are allowed as template argument for OutputIterator. If you take instead e.g. the cppreference.com page for std::copy_if, you see that it specifies that the type must be a LegacyOutputIterator (aka an output iterator).
This is a term describing specific requirements that the type must satisfy in order to be allowed to be used with std::copy_if.
An output iterator type is just an iterator type which allows writing to the dereferenced iterator.
For the details see https://en.cppreference.com/w/cpp/named_req/OutputIterator.
On the page you linked for std::back_inserter, it says that it is a function returning a std::back_insert_iterator. When you use std::back_inserter(...) in the argument list of std::copy_if, you are passing it this returned object, not the std::back_inserter itself.
If you click on the name of that type on the linked page, you will see that it specifies that std::back_insert_iterator is a LegacyOutputIterator.
So, it is allowed to be used in std::copy_if.
std::ostream_iterator is also an output iterator and therefore usable in std::copy_if. It is only used to "iterate" and write to std::ostream streams. It is not related to std::back_inserter. It is not related to std::vector either and you are not using it in your example.
"Iterate" here is not quite correct, because it doesn’t really iterate anything. When writing to the dereferenced std::ostream_iterator it simply outputs the value to the associated std::ostream. This is why it says that ++ on it is a noop. There is nothing to do to advance it.