'How to use remove_if on an std::list of structs when you want to compare to a member variable of the struct
I have an std::list
of structs and I would like to remove items from the list based on if a certain member variable matches a particular value.
My struct and list:
struct Foo
{
uint64_t PID;
uintptr_t addr;
};
std::list<Foo> FooList;
Code to remove entry:
uintptr_t Bar;
FooList.remove_if(???) // Remove when "Foo.addr == Bar";
I'm not sure how to reference to the struct instance inside of the remove_if()
function, any help would be appreciated!
Thanks,
Naitzirch
Solution 1:[1]
list::remove_if
takes a function object as its argument. You can feed with an inline lambda function like this:
FooList.remove_if([Bar] (auto &element) {
return element.addr == Bar;
});
Edit: be advised that if Bar
is a local variable declared outside if the lambda, you need to capture it via copy (Bar
) or reference (&Bar
) within the lambda capture list (the leading square brackets)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |