[英]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. 我正在尝试在对象指针的Vector中找到某个对象。 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. 可以说,出于我的目的,如果2个类的“ x”值相同,则它们相等。 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.
因此,在上面的代码中,我想在STL find_if()方法中使用谓词,以便能够“查找”向量中的c4。
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. find_if
使用一元谓词,而不是二进制谓词。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.