Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading