No, not really. ostream_iterator
isn't configurable like that.
So you'll have to use the pre-space "workaround" as found in other answers, and manually chop off that final line.
BTW It's been noted that &v[3]
, strictly speaking, invokes undefined behaviour due to the implicit dereference in the sub-expression v[3]
. Prefer &v[0]+3
(or just v+3
) — "having" a pointer to one-past-the-end of an array is okay, as long as it's not dereferenced.
You could make your own kind of ostream_iterator
that does this, as the following example demonstrates.
Yes, it's verbose; however, you can also change it around however you like to suit your changing needs:
#include <iostream>
#include <iterator>
#include <algorithm>
template <class T, class charT = char, class traits = std::char_traits<charT> >
struct ostream_iterator_x
: std::iterator<std::output_iterator_tag, void, void, void, void> {
typedef charT char_type;
typedef traits traits_type;
typedef std::basic_ostream<charT,traits> ostream_type;
ostream_iterator_x(ostream_type& s, const charT* pre = 0, const charT* post = 0)
: s(s)
, pre(pre)
, post(post) {};
ostream_iterator_x(const ostream_iterator_x& x)
: s(x.s)
, pre(x.pre)
, post(x.post) {};
~ostream_iterator_x() {}
ostream_iterator_x& operator=(const T& value) {
if (pre != 0) s << pre;
s << value;
if (post != 0) s << post;
return *this;
}
ostream_iterator_x& operator*() { return *this; }
ostream_iterator_x& operator++() { return *this; }
ostream_iterator_x& operator++(int) { return *this; }
private:
ostream_type& s;
const charT* pre;
const charT* post;
};
int main()
{
int v[] = { 1, 2, 3 };
std::copy(v, v+3, ostream_iterator_x<int>(std::cout, " ", "\n"));
}
// Output:
// 1
// 2
// 3
(I used [n3290: 24.6/2]
to determine the members and base-specification required for this to work and to be standard-compliant.)