Spe*_*eed 26 c++ stl stl-algorithm
我有一个代表一个被调用的用户的类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";
}
Run Code Online (Sandbox Code Playgroud)
我已经超载了== operator
所以比较Nick == Nick2应该工作,但函数返回error C2678: binary '==' : no operator found which takes a left-hand operand of type 'Nick' (or there is no acceptable conversion)
.
这是我的Nick课程供参考:
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);
};
};
Run Code Online (Sandbox Code Playgroud)
mka*_*aes 39
如果您使用的是C++ 0X,则可以使用简单的lambda表达式
std::string username = "Nicholas";
std::find_if(userlist.begin(), userlist.end(), [username](Nick const& n){
return n.username == username;
})
Run Code Online (Sandbox Code Playgroud)
Nik*_*kko 16
您必须使用类外的两个对象定义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;
}
Run Code Online (Sandbox Code Playgroud)
你的发现应该是这样的:
std::find(userlist.begin(), userlist.end(), Nick(username, false) );
Run Code Online (Sandbox Code Playgroud)
不需要"新".
我知道你想重载==
运算符,但是使用谓词可以轻松完成同样的事情:
struct UsernameIs {
UsernameIs( string s ) : toFind(s) { }
bool operator() (const Nick &n)
{ return n.username == toFind; }
string toFind;
};
int main()
{
vector<Nick> vn(10);
string nameToFind = "something";
find_if(vn.begin(), vn.end(), UsernameIs(nameToFind));
}
Run Code Online (Sandbox Code Playgroud)
请注意,在C++ 0x中,您可以更简洁地使用lambda表达式执行相同的操作.