Re: Print map values with class as map member
Carl Barron wrote:
In article <1156643171.935106.29900@h48g2000cwc.googlegroups.com>,
<testcpp@gmail.com> wrote:
I am new at C++ and have been trying to understand maps by
developing a small program but I cannot determine how to
print out the values stored in the maps. Once I understand
how maps work, I'll move on to hashing tables, just so that
I get the understanding of their operation.
I'm having an issue and I think what I am attempting to
perform is not capable. I am attempting to create a class
and then use that same class as member of a map. The
standard doesn't seem to not allow what I'm attempting to
perform but it doesn't work somehow:
[snip]
class M {
public:
M() {};
M(int, vector<int>) {int i = 0; vector <int> table2;};
~M() {};
private:
int i;
vector<int> mv;
};
ostream& operator<<(ostream &output, const int &x, const map<int, M>
&y) {
output << x << endl << y;
return output;
};
This has an invalid signature operator << takes two args not three.
Even if it didn't, there is no << for a map (his third
parameter).
you can accomplish this with explicitly << x and << y if you write a
proper operator << (std::ostream &,std::map<...> const &) except map
and ostream are in namespace std and your operator << is not so it
won't be found.
Except that he will be using std::map<int,M>, so functions
and/or operators in the same namespace as M should be found.
After that, it's a question of overload resolution. Something
like the following should work:
std::ostream&
operator<<( std::ostream& dest, std::map< int, M > const& obj )
{
for ( std::map< int, M >::const_iterator iter = obj.begin() ;
iter != obj.end() ;
++ iter ) {
dest << iter->first << ':' << iter->second << '\n' ;
}
return dest ;
}
Of course, that's only true if one of the arguments to the
std::map template is a user defined type. The above won't work
for std::map< int, std::string >, nor for std::map< int,
std::vector< int > >.
/* This will not work, a failed attempt.
ostream& operator<<(ostream &output, const &vector<int> mv ) {
output << x;
return output;
};
*/
std::ostream & operator << (std::ostream &os, const std::vector<int
&mv)
{
std::copy(m.begin(),m.end(),std::ostream_iterator<int>(os,"\n"));
return os;
}
[snip]
Except that ADL will NOT find this operator<<. He'd need to put
it in namespace std, which is illegal.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]