Array iteration ensure fail

Thank you for helping, however, I am unsure how to go about what you are saying. I tried to store Item in a new FInventoryItem (the Struct) variable and modify the Quantity after the for loop, however, that didn’t work, I was unable to update the quantity of the item in the array.

Here is my current code, which works and can even make a new stack of the item if the Quantity is over the maximum:



 for (auto& Item : InventorytoAdd->Inventory)
                        {
                            if (Item.ItemID == ItemToAdd->ItemID) // If the item's ID in inventory matches the Added Item's ID 
                            {
                                if (Item.Quantity < Item.MaxStackSize)
                                {
                                    if (Item.Quantity + ItemToAdd->Quantity > Item.MaxStackSize) //If the sum of the two Item's Quantities is greater than the max stack size
                                    {
                                        int32 AddedItemInitialQuantity = ItemToAdd->Quantity;
                                        int32 QuantitytoAdd = Item.Quantity + ItemToAdd->Quantity - Item.MaxStackSize;
                                        Item.Quantity = Item.MaxStackSize; // Set the Item in inventory's quantity to the maximum
                                        ItemToAdd->Quantity = QuantitytoAdd; // Give the added Item the rest of the quantity that is over the maximum
                                        InventorytoAdd->Inventory.Add(*ItemToAdd); //Add the Item with the updated quantity
                                        ItemToAdd->Quantity = AddedItemInitialQuantity;
                                        return;
                                    }
                                    else if (Item.Quantity < Item.MaxStackSize)
                                    {
                                        Item.Quantity = Item.Quantity + ItemToAdd->Quantity;
                                        return;
                                    }
                                }
                            }
                        }


Even though this works, as I said I am still pretty new to programming and definitely don’t want to be using bad practices. How would I keep a separate list of the items in the inventory?

Thanks again.