I was wondering if anyone would be able to help me out with regards to printing out a list of a custom class (first time using containers).
Currently I have a variable declared as:
std::list<Item> inventory;
within a class called player.
Now I have created a function within the class (player) called void printInventory();.
So my question is how do I go about printing what is in that list.
My Item class contains 3 variables;
std::string name;
int damage;
int value;
I also have a function to print these variables void itemDetails();
Any help is much appreciated.
Edit:
I know have solved my problem with thanks to the answers provided, here’s what i did:
Overloaded the output operator in the item class:
ostream& operator<<(ostream& os, const Item& item)
{
if (item.getTypeInt() == 0)
{
os << "Name: " << item.getName() << endl
<< "Type: " << item.getTypeString() << endl
<< "Damage: " << item.getDamage()<< endl
<< "Value: " << item.getValue() << endl;
}
else
{
os << "Name: " << item.getName() << endl
<< "Type: " << item.getTypeString() << endl
<< "HP: " << item.getHP()<< endl
<< "Value: " << item.getValue() << endl;
}
return os;
}
I then used one of the answers but modified it so it wasn’t declaring another variable:
void Player::printInventory()
{
for(std::list<Item>::iterator it = inventory.begin(); it!= inventory.end(); ++it)
{
cout << *it;
}
cout <<"Inventroy Printed!!"<<endl;
}
You should overload
std::ostream& operator<<forItemandplayer, this will allow you to write the data to streams other than stdout. Here’s an example:This allows you to do
Then, you implement a similar operator for
player, looping over the list and printing each item.