1

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

Evg
  • 25,259
  • 5
  • 41
  • 83
Naitzirch
  • 45
  • 1
  • 2
  • 6

1 Answers1

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)

The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49
  • Awesome! It worked, thanks. Also note the semi-colons on your second and third line ;) – Naitzirch Apr 24 '22 at 14:18
  • @Naitzirch nice catch. Fixed – The Dreams Wind Apr 24 '22 at 15:43
  • 1
    There shouldn't be a `=` for `=Bar`. It should just be `Bar`. `=` is only used to allow default capture of all used variables. – François Andrieux Apr 24 '22 at 18:06
  • @FrançoisAndrieux you are most likely right, since it doesn't have such notation in the reference documents, however Stroustrup uses it in his **A Tour of C++**: *Had we wanted to give the generated object a copy of x, we could have said so: [=x]*. 6.3.3 Lambda Expressions – The Dreams Wind Apr 24 '22 at 21:13