使用STL find_if()在对象指针的Vector中查找特定对象
Use STL find_if() to find a specific object in a Vector of object pointers
我试图在对象指针的向量中找到某个对象。假设这些是我的类。
// 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);
}
让我们说,为了我的目的,两个类的对象是相等的,如果他们的'x'值是相同的。因此,在上面的代码中,我想在STL find_if()方法中使用谓词,以便能够在向量中"找到"c4。
我似乎不能得到一个谓词工作。我的find谓词基于我为排序而编写的谓词。
struct less{
bool operator()(Class *c1, Class *c2){return *c1 < *c2;}
};
sort(set.begin(), set.end(), less());
这个排序谓词工作良好。所以我将它用于查找
struct eq{
bool operator()(Class *c1, Class *c2){return *c1 == *c2;}
};
为什么这个谓词不起作用?写这个谓词的更好的方法是什么?
谢谢
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));
相关文章:
- 对象指针在c++中是如何工作的
- C++ 对象指针数组的复制构造函数
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 正确初始化和销毁对象指针的C++数组?
- 如何深度复制链表对象指针
- 对象指针 c++ 的全局向量错误
- 如何将 c++ 类包装到 python 中,以便我可以使用 pybind11 访问其成员的公共方法(成员是一个对象指针)
- 静态对象指针
- 正在将对象指针数组初始化为NULL
- 如何使用条件表达式返回对象指针?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 使用C对象指针构建PyObject*
- 如何在使用对象指针时访问成员函数
- 静态强制转换允许转换对象指针,但不允许转换整数
- C++ abort() 在函数内的抽象类对象指针调用上
- 指向函数的对象指针
- 访问指向对象指针向量的指针的第一个元素?
- 如何将对象/指针正确存储到 Qlist 中
- 对象指针打印结果以相反的顺序进行