且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用std :: find / std :: find_if与自定义类对象的向量?

更新时间:2022-11-19 21:43:00

你的类,作为一个工具函数,不是一个成员。

You have to define operator== with two Objects outside your class, as a tool function, not a member.

然后让它的朋友只是把函数的声明放在类中。

Then to make it friend just put the declaration of the function inside the class.

class Nick {

public:
    friend bool operator== ( const Nick &n1, const Nick &n2);
};


bool operator== ( const Nick &n1, const Nick &n2) 
{
        return n1.username == n2.username;
}

此外,您的查找应如下所示:

Also your find should look like this:

std::find(userlist.begin(), userlist.end(), Nick(username, false) );

不需要新。