如何使用std :: find / std :: find_if与自定义类对象的向量? [英] How to use std::find/std::find_if with a vector of custom class objects?

查看:373
本文介绍了如何使用std :: find / std :: find_if与自定义类对象的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类代表一个名为 Nick 的用户,我想使用 std :: find_if 其中我想找到userlist向量是否包含与我传入的相同的用户名对象。我做了一些尝试,试图创建一个新的 Nick 对象的用户名我想测试和重载 ==运算符,然后尝试在对象上使用 find / find_if



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 included with the same username I pass in. I did a few attempts by trying to create a new Nick object for the username I want to test and overloading the == operator and then trying to use find/find_if on the object:

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

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



我已经重载 ==运算符所以比较Nick == Nick2应该工作,但函数返回错误C2678:二进制'==':无操作符找到一个左手操作数类型'Nick'是不可接受的转换)

I have overloaded the == operator so comparing Nick == Nick2 should work, but the function returns error C2678: binary '==' : no operator found which takes a left-hand operand of type 'Nick' (or there is no acceptable conversion).

这是我的Nick类供参考:

Here is my Nick class for reference:

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


推荐答案

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

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

不需要新。

这篇关于如何使用std :: find / std :: find_if与自定义类对象的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆