我有一个代表名为 Nick
的用户的类,我想在其上使用 std::find_if
,我想在其中查找用户列表 vector 是否有对象包含在我传入的相同用户名中。我尝试为我要测试的用户名创建一个新的 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 take a left- 'Nick' 类型的手动操作数(或没有可接受的转换)
.
这是我的 Nick 类(class)供引用:
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);
};
};
最佳答案
如果您使用的是 C++0X,则可以使用简单的 lambda 表达式
std::string username = "Nicholas";
std::find_if(userlist.begin(), userlist.end(), [username](Nick const& n){
return n.username == username;
})
关于STL - 如何将 std::find/std::find_if 与自定义类对象 vector 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6939129/