c++11lambdastdpass-by-pointerpass-by-const-reference

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)


Solution

  • You want to have const reference to pointer, not reference to const pointer:

    [](obj* const& instance) { if(instance->a == 5) return true; return false; }
    

    or with type alias for obj pointer, it is much clearer:

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