ostream_iterator for map
I feel like I've asked this question before, but if so I can't find it
and still don't get it, so here goes....
I want to copy a std::map to std::cout. I define operator<< for the
map's value_type. I can use that operator by defererencing a the map's
iterator. Why can't I compile std::copy with ostream_iterator?
The program that follows compiles and runs as is. Change it to #if 0
instead, and get "no match for 'operator<<' ". g++ says there are many
candidates, all standard, none mine.
The whole "no match" error is:
/usr/include/g++/bits/stream_iterator.h:196: error: no match for
'operator<<' in '*((std::ostream_iterator<std::pair<const int, float>,
char, std::char_traits<char> >*)
this)->std::ostream_iterator<std::pair<const int, float>, char,
std::char_traits<char> >::_M_stream << __value'
Many thanks for your insight.
--jkl
#include <map>
#include <iostream>
#include<iterator>
using namespace std;
typedef map<int,float> the_map;
ostream& operator<<( ostream& os, const the_map::value_type& value )
{
return os << "(" << value.first << ", " << value.second << ")";
}
int main( int argc, char *argv[] )
{
the_map m;
m[1] = 1.0F;
#if 1
cout << *m.begin() << endl;
#else
copy( m.begin(), m.end(),
ostream_iterator<the_map::value_type>(cout, "\n") );
#endif
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]