简体   繁体   中英

Use STL find_if() to find a specific object in a Vector of object pointers

I'm trying to find a certain object in a Vector of object pointers. Lets say these are my classes.

// Class.h
class Class{
public:
    int x;
    Class(int xx);
    bool operator==(const Class &other) const;
    bool operator<(const Class &other) const;
};

// Class.cpp
#include "Class.h"
Class::Class(int xx){
    x = xx;
}

bool Class::operator==(const Class &other) const {
    return (this->x == other.x);
}

bool Class::operator<(const Class &other) const {
    return (this->x < other.x);
}

// Main.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include "Class.h"
using namespace std;

int main(){
    vector<Class*> set;
    Class *c1 = new Class(55);
    Class *c2 = new Class(34);
    Class *c3 = new Class(67);
    set.push_back(c31);
    set.push_back(c32);
    set.push_back(c33);

    Class *c4 = new Class(34);
}

Lets say that for my purposes, 2 objects of class are equal if their 'x' values are the same. So in the above code, i'd like to use a predicate in the STL find_if() method to be able to 'find' c4 in the vector.

I can't seem to get a predicate to work. I'm basing my find predicate on the predicate I wrote for sorting.

struct less{
    bool operator()(Class *c1, Class *c2){return  *c1 < *c2;}   
};
sort(set.begin(), set.end(), less());

This sorting predicate works fine. So I adapted it to use for finding

struct eq{
    bool operator()(Class *c1, Class *c2){return  *c1 == *c2;}  
};

Why won't this predicate work? What is the better way of writing a predicate for this?

Thanks

find_if takes a unary predicate, NOT a binary predicate.

struct eq{
    eq(const Class* compare_to) : compare_to_(compare_to) { }
    bool operator()(Class *c1) const {return  *c1 == *compare_to_;}  
private:
    const Class* compare_to_;
};

std::find_if(set.begin(), set.end(), eq(c4));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM