Re: Print map values with class as map member
In article <1156643171.935106.29900@h48g2000cwc.googlegroups.com>,
<testcpp@gmail.com> wrote:
Hi,
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.
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.
solution [fairly safe ] is a struct
struct my_map:std::map<int,M>{};
should get around this if you only default construct the map.
std::ostream & operator << (std::ostream &os,my_map const &m)
{
for(my_map::const_iterator it=m.begin();it!=m.end();++i)
os << it->first << ' ' << it->second << '\n';
return os;
}
/* 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]
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]