Print map values with class as map member
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:
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
#include<map>
using std::map;
#include <string>
using std::string;
#include <vector>
using std::vector;
/* Class M to be used as part of map. */
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 will not work, a failed attempt.
ostream& operator<<(ostream &output, const &vector<int> mv ) {
output << x;
return output;
};
*/
int main()
{
vector<int> table1;
M t(20, table1); // generic values
// this was from an earlier programme to just get maps to work
okay.
table1.push_back(1);
table1.push_back(2);
table1.push_back(3);
map<int, M> map_test;
map_test[20] = t;
typedef map<int, M>::const_iterator con_it;
for( con_it x = map_test.begin(); x !=map_test.end(); ++x ) {
cout << x->first << endl << x->second << endl;
}
}
If I leave out this section:
typedef map<int, M>::const_iterator con_it;
for( con_it x = map_test.begin(); x !=map_test.end(); ++x ) {
cout << x->first << endl << x->second << endl;
The programme compiles and builds correctly. Once I add it in (without
the overloaded << operator), I have linker errors indicating that the
compiler cannot find an << operator that takes an int and a const "M."
As a work around, I've attempted to create an overloaded << operator to
accomodate my user defined map, but nothing seems to work correctly.
I've tried several things including:
1. Created two separate overloaded operators, one for the two parts of
the map: an int and a vector.
2. Created an overloaded << operator with the following parameters:
ostream, int, ostream and vector. (as const and non-const references)
3. Created an overloaded << operator with the following parameters:
ostream, map.
Am I attempting something not capable of working, that is using a class
as a member of a map? If I remove the class and just build a simple
map with two ints as members, I have no trouble. I've spent several
days on this but am not making much progress and would like to move on
to hash tables and learn those.
Could someone please suggest some feedback?
Kimi
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]