Search code examples
c++vectorlambdafindpointer-to-member

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


I'm trying to traverse through a vector of "Stimulus" class objects. And if the properties of the object match the criteria, I want that Stimulus object returned.

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

The code above gives me a compile error : must use '.' or '->' to call pointer-to-member function in..... What am I doing wrong? Or what should I do differently to avoid this altogether?


Solution

  • you have to specify the instance, either by using a lambda (see below) or 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); });
        }
    }
    

    (for C++14, change const auto& to const Stimulus& for older versions)