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

标签 stl stl-algorithm c++

我有一个代表名为 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/

相关文章:

c++ - 对我的类(class)实现删除功能

c++ - `iterator` 和 `const_iterator` 不是 STL 容器的必需成员吗?

c++ - E2316 'any_of' 不是 'std' 的成员

c++ - 通过对 C++ 线程的引用传递局部变量

c++ - 字符串中最优化的连接方式

c++随时通过按键跳出循环

c++ - 在以下情况下,集合插入如何工作?

C++ 标准库可移植性

algorithm - 为什么是 `copy_n` 、 `fill_n` 和 `generate_n` ?

c++ - 将带有两个参数的成员函数传递给 C++ STL 算法 stable_partition