How to use std::find/std::find_if with a vector of custom class objects?

前端 未结 6 697
故里飘歌
故里飘歌 2020-11-29 04:09

I have a class representing a user called Nick and I want to use std::find_if on it, where I want to find if the userlist vector has an object incl

6条回答
  •  星月不相逢
    2020-11-29 04:39

    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.

    try something like this:

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

    No need of "new".

提交回复
热议问题