Hi guys, so basically I am trying to write a code which check to see if the player has any items in their inventory, and if so, keep checking until it reaches a place where the element is empty and simply input the text "Empty" for now. Here is my attempt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int sizeofinv = 0;
constint max = 10;
vector<string> inventory;
inventory.reserve(MAX_ITEMS);
inventory.push_back("Health Potion"); //Give player one health pot by default
for (int i = 0; i < MAX_ITEMS; ++i)
{
if (!inventory[i].empty())
{
++sizeofinv;
}
else
{
inventory.push_back("Empty");
}
}
So for example, player opens their inventory and see something like this: (your inventory: Health Potion, Empty, Empty, Empty... etc)
The reserve function just allocates enough memory to store all MAX_ITEMS elements but the size of the vector stays the same and the elements beyond the elements that you have will not be automatically created so you should not try to access them by index as you do in the code.
What you can do instead is to use the size function to decide on what index the loop should start and by doing so you skip the already inserted items so that you don't need to check anything before inserting "Empty".
1 2 3 4 5
sizeofinv = inventory.size();
for (int i = sizeofinv; i < MAX_ITEMS; ++i)
{
inventory.push_back("Empty");
}
What you are doing here is that you resize the vector to a certain size and set all new elements to some default value. You can do the exact same thing using the resize function.
If all Empty spots are always at the end of the inventory (you never have something like "Health Potion", "Empty", "Mana Potion", ...) then I think it would probably be easier to only store items and not the "empty" placeholders in the vector. You wouldn't need the sizeofinv variable because the size function of the vector would give you the same information. If you want to print the items in the inventory you would just need to loop though the items as normal and then use another loop to loop from inventory.size() to MAX_ITEMS and output the string "Empty" (without accessing the elements of the vector).
I agree with the others that you should not place "empty" strings in your vector. You should depend on the vector's size() function to tell you how many items the player has.
I would also suggest separating the creation of the inventory and the display of the inventory.
Something along these lines: