【问题标题】:Use STL find_if() to find a specific object in a Vector of object pointers使用 STL find_if() 在对象指针向量中查找特定对象
【发布时间】:2011-05-07 00:24:46
【问题描述】:

我试图在对象指针向量中找到某个对象。 假设这些是我的课程。

// 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”值相同,则 2 个类对象是相等的。所以在上面的代码中,我想在 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;}  
};

为什么这个谓词不起作用? 为此编写谓词的更好方法是什么?

谢谢

【问题讨论】:

  • 当您尝试使用该谓词时发生了什么?它编译了吗?是否产生了超出预期的结果?
  • 乍一看,您的代码在我看来还不错,但为什么要将指针存储在向量中?只存储对象本身通常更简单、更高效、更安全。
  • 如果你破解你的谓词打印出c1-&gt;xc2-&gt;x会发生什么?
  • 另外,你在标题中说find,但在问题文本中说find_if(你也没有显示你是如何称呼的),所以它是什么,你怎么称呼是吗?
  • STL 不使用命名空间std

标签: c++ stl


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 2011-10-01
    • 2011-02-11
    • 2013-03-14
    • 1970-01-01
    • 2022-11-13
    相关资源
    最近更新 更多