如何用find_if找到一个class的匹配对象? (或任何其他方式来实现的结果)

How to use find_if to find a matching object of a class? (Or any other way to achieve the result)

我正在尝试遍历 "Stimulus" class 个对象的向量。如果对象的属性符合条件,我希望返回 Stimulus 对象。

std::vector<Stimulus> BS_stimulus_list;

bool StimulusCollection::isNextPoint(Stimulus it){
if(it.GetPointDeg()=="(Some json value)" & it.GetEye()==currentEye){
    return true;
}
else{
    return false;
}

void StimulusCollection::NextBSStimulus(char e){
currentEye = e;
if (currentEye=='L'){
    vector<Stimulus>::iterator idx = find_if(BS_stimulus_list.begin(), BS_stimulus_list.end(),isNextPoint);
}

上面的代码给我一个编译错误:必须使用'.'或'->'来调用指向成员函数的指针...... 我究竟做错了什么?或者我应该做些什么来完全避免这种情况?

假设isNextPoint被标记为static,你需要明确限定它:

find_if(BS_stimulus_list.begin(), 
        BS_stimulus_list.end(), 
        StimulusCollection::isNextPoint)

如果不是 static,您可以使用 lambda 表达式 以便将 isNextPoint 的调用绑定到 [=15= 的特定实例].

您必须通过使用 lambda(见下文)或 std::bind

来指定实例
void StimulusCollection::NextBSStimulus(char e) {
    currentEye = e;
    if (currentEye=='L'){
        vector<Stimulus>::iterator idx = find_if(
            BS_stimulus_list.begin(), 
            BS_stimulus_list.end(),
            [this](const auto& stimulus) { return isNextPoint(stimulus); });
    }
}

(对于 C++14,对于旧版本,将 const auto& 更改为 const Stimulus&