簡體   English   中英

使用STL find_if()在對象指針的Vector中查找特定的對象

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

我正在嘗試在對象指針的Vector中找到某個對象。 可以說這些是我的課程。

// 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()方法中使用謂詞,以便能夠“查找”向量中的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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM