mardi 5 octobre 2021

Using find_if with a vector of pointers: How to pass pointer by const reference to lambda?

In the following code I try to compare a vector of pointers via find_if and determine which contains a member a == 5 (in this case both of course, but it shows my case). However it doesn't compile.

#include <algorithm>

class obj
{
    public:
    int a = 5;
    int b = 2;
};

int main()
{
    obj A;
    obj B;
    std::vector<obj*> v = { &A, &B };

    std::find_if(begin(v), end(v), [](const (obj*)& instance) { if((*instance)->a == 5) return true; });
}

From what I interpreted here, find_if provides the actual vector entry as parameter to the lambda function which is traditionally taken up via const ref. But how do I specify this for pointers, because I have pointers as vector entries?

(For the lengthy error message take this code to godbolt using gcc 11.1 but I guess it's down to me not knowing how to specify the lambda argument correctly)

Aucun commentaire:

Enregistrer un commentaire