How to write out my element in list?

My for loop code is looking like this.
I have been trying to find how I can write out the *rit! I know how to do it when it comes to when the list is containg int and string but now I have been doing my own class cd and that has in parameters(string name, string song).
It also has a printing function in it so it write out name and song.

I hope somebody can help med with this.

1
2
3
4
5
6
   cout << "mylist contains:";
            list<cd>::reverse_iterator rit;
            for ( rit=l1.rbegin() ; rit != l1.rend(); ++rit ){
                 cd c = *rit;

                cout << endl;
You say your class has a print function. All you have to do is call it.
At line 5:
 
  c.print ();


The more elegant way to do this is to have your class overload the << operator. That way you can wirte:
 
  cout << cd << endl;


To do that you need to have a friend function in your class declaration
 
  friend ostream & operator << (ostream & os, const cd & _cd);


And then implement the following function:
1
2
3
4
ostream & operator << (ostream & os, const cd & _cd)
{ _cd.print(os);
   return os;
}

Note that I've changed print to accept an ostream reference.

You made my day!!!
Topic archived. No new replies allowed.