如何使用std :: find / std :: find

编程入门 行业动态 更新时间:2024-10-12 03:22:15
本文介绍了如何使用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

本文发布于:2023-11-30 14:38:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650356.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   std   find

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!