ostreams and vector<vector>s

R

Russ Ford

I'm trying to overload the << operator to output vectors, as follows:

template <class T>
ostream& operator << (ostream& o, const vector<T>& v)
{
o << "< ";
copy (v.begin(), v.end(), ostream_iterator<T>(o, " ");
return o << ">";
}

This works well, except for outputting a vector<vector> where compile errors
occur. The STL reference says that the ostream_iterator will work for any
type T where cout << T is defined. Doesn't the above define cout << for a
vector?

If I define like this instead,

template <class T>
ostream& operator << (ostream& o, const vector<T>& v)
{
o << "< ";
vector<T>::const_iterator i;
for (i=v.begin(); i<v.end(); ++i) cout << *i << " ";
return o << ">";
}

it works fine. What gives?

Russ
 
D

David Hilsee

Russ Ford said:
I'm trying to overload the << operator to output vectors, as follows:

template <class T>
ostream& operator << (ostream& o, const vector<T>& v)
{
o << "< ";
copy (v.begin(), v.end(), ostream_iterator<T>(o, " ");
return o << ">";
}

This works well, except for outputting a vector<vector> where compile errors
occur. The STL reference says that the ostream_iterator will work for any
type T where cout << T is defined. Doesn't the above define cout << for a
vector?

If I define like this instead,

template <class T>
ostream& operator << (ostream& o, const vector<T>& v)
{
o << "< ";
vector<T>::const_iterator i;
for (i=v.begin(); i<v.end(); ++i) cout << *i << " ";
return o << ">";
}

it works fine. What gives?

This is a common question. A simple googling (http://groups.google.com) of
the comp.lang.c++.* groups for ostream_iterator provides many explanations
(e.g. Adrian Sandor's post and news_user's post).
 
J

Jonathan Turkanis

Russ Ford said:
I'm trying to overload the << operator to output vectors, as follows:

template <class T>
ostream& operator << (ostream& o, const vector<T>& v)
{
o << "< ";
copy (v.begin(), v.end(), ostream_iterator<T>(o, " ");
return o << ">";
}

Reece Dunne's Output Formatters library, up for review for inclusion in boost
begining Sept 12, handles this type of problem nicely, with the capacity much
customization.

If you are interested, the library is available in the boost sandbox
(http://www.boost.org/more/mailing_lists.htm#sandbox) . The docs are here:
http://tinyurl.com/4mu39.

Jonathan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top