c++ - 使用 STL find_if() 在对象指针 Vector 中查找特定对象

标签 c++ stl

我试图在对象指针 vector 中找到某个对象。 可以说这些是我的类(class)。

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

可以说,就我的目的而言,如果类的 2 个对象的“x”值相同,则它们相等。因此,在上面的代码中,我想在 STL find_if() 方法中使用谓词,以便能够在 vector 中“查找”c4。

我似乎无法让谓词发挥作用。我的查找谓词基于我为排序编写的谓词。

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++ - 使用 STL find_if() 在对象指针 Vector 中查找特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5914012/

相关文章:

c++ - 如何将 "cast"std::vector<char> 转换为 std::vector<wchar_t>

c++ - ARM Embedded Linux (AM335x),断电后文本文件内容被删除

c++ - 在我的机器上操作大 vector 时 CUDA 推力变慢

c++ - boost::thread 构建错误(无法链接 lib && 未解析的外部)

c++ - 是否可以创建指针 vector ?

c++ - 如何在 STL 中使用 libclang?

c++ - 2-prop 排序列表的正确数据结构是什么?

c++ - 普通数组与指针数组

c++ - 是否可以将 MongoDB 用作嵌入式数据库?

c++ - 两个静态库,两个不同的 vector 实现,链接器会做什么?