Reputation: 15
I want to convert a function body into a lambda. But I don't know how you can implement this if statement into the lambda. I also dont know what is the best to use for this. Is it better to use std::find_if, std::find or something else.
void Inventory::RemoveFromInventory(std::string item)
{
//--bool to check if an item is in the inventory
bool found = false;
for (std::list<Item>::iterator i = m_Inventory.begin(); i != m_Inventory.end(); i++)
{
if (i->GetName() == item)
{
m_Inventory.erase(i);
found = true;
break;
}
}
if (found == false)
{
std::cout << "item not in inventory!" << std::endl;
}
}
Cann someone help me with this conversion problem?
Upvotes: 0
Views: 60
Reputation: 63124
So you want to search for an item that verifies a condition, check whether you found it, and erase it. That's a use case for std::find_if
:
void Inventory::RemoveFromInventory(std::string item)
{
auto const foundAt = std::find_if(
begin(m_Inventory),
end(m_Inventory),
[&](Item const &i) { return i.GetName() == item; }
);
if(foundAt == end(m_Inventory)) {
std::cout << "item not in inventory!\n";
} else {
m_Inventory.erase(foundAt);
}
}
Upvotes: 3