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

新手上路,请多包涵

我有一个代表名为 Nick 的用户的类,我想在其上使用 std::find_if ,我想在其中查找用户列表向量是否包含与我传入的相同用户名的对象我做了一些尝试,尝试为我要测试的用户名创建一个新的 Nick 对象并重载 == operator 然后尝试使用 find/find_if 物体:

     std::vector<Nick> userlist;
    std::string username = "Nicholas";

if (std::find(userlist.begin(), userlist.end(), new Nick(username, false)) != userlist.end())) {
    std::cout << "found";
}

我已经超载了 == operator 所以比较 Nick == Nick2 应该可以工作,但是函数返回 error C2678: binary '==' : no operator found which takes a left-hand operand of type 'Nick' (or there is no acceptable conversion)

这是我的尼克课程供参考:

 class Nick {
private:
    Nick() {
        username = interest = email = "";
                    is_op = false;
    };
public:
    std::string username;
    std::string interest;
    std::string email;
    bool is_op;

    Nick(std::string d_username, std::string d_interest, std::string d_email, bool d_is_op) {
        Nick();
        username = d_username;
        interest = d_interest;
        email = d_email;
        is_op = d_is_op;
    };
    Nick(std::string d_username, bool d_is_op) {
        Nick();
        username = d_username;
        is_op = d_is_op;
    };
    friend bool operator== (Nick &n1, Nick &n2) {
        return (n1.username == n2.username);
    };
    friend bool operator!= (Nick &n1, Nick &n2) {
        return !(n1 == n2);
    };
};

原文由 Speed 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 971
2 个回答

您必须使用类外部的两个对象定义 operator== 作为工具函数,而不是成员。

然后让它成为朋友,只需将函数的声明放在类中。

尝试这样的事情:

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

你的发现也应该是这样的:

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

不需要“新”。

原文由 Nikko 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您使用的是 C++0X,则可以使用简单的 lambda 表达式

std::string username = "Nicholas";
std::find_if(userlist.begin(), userlist.end(), [username](Nick const& n){
    return n.username == username;
})

原文由 mkaes 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题