将 find_if 与指针向量一起使用:如何通过 const 引用将指针传递给 lambda?

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

在下面的代码中,我尝试通过 find_if 比较一个指针向量,并确定其中包含一个成员 a == 5(在这种情况下当然是两种情况,但它显示了我的情况)。但是它不编译。

#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; });
}

根据我的解释 ,find_if 将实际向量条目作为参数提供给 lambda 函数,传统上通过 const ref 使用。但是我如何为指针指定它,因为我有指针作为向量条目?

(对于冗长的错误消息,请使用 gcc 11.1 将此代码转至 godbolt,但我想这是因为我不知道如何正确指定 lambda 参数)

你想要对指针的常量引用,而不是对常量指针的引用:

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

或者obj指针的类型别名,更清晰:

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