【问题标题】:Compare string object equals to element in vector比较字符串对象等于向量中的元素
【发布时间】:2017-05-06 09:41:39
【问题描述】:

所以我是 C++ 的新手,这让我有点不知所措。所以我需要帮助。我正在尝试搜索 String objectin vector<Objects> 并查看它们是否相等。正在搜索,我决定使用 c++11 lamba 表达式,它不断给我错误:

    Severity    Code    Description Project File    Line    Suppression State
Error   C3867   'User::getEmail': non-standard syntax; use '&' to create a pointer to member    EmailServerClientApp    c:\users\user\desktop\emailserverclientapp\emailserverclientapp\guinterface.cpp 110 

    Severity    Code    Description Project File    Line    Suppression State
Error   C2678   binary '==': no operator found which takes a left-hand operand of type 'overloaded-function' (or there is no acceptable conversion) EmailServerClientApp    c:\users\user\desktop\emailserverclientapp\emailserverclientapp\guinterface.cpp 110 

我创建了一个重载运算符(或者至少根据我对 c++ 的了解,我认为我做到了)。看不出这有什么问题。

这是我的用户类:

    private:
    string userName;
    string password;
    string email;

public:
    User();
    User(string name, string pass, string e);

    void setUserName(string name);
    void setPassword(string pass);
    void setEmail(string e);
    bool numberInString(const std::string& s);
    void print()const;

    User &operator=(User other)
    {
        std::cout << "copy assignment of Email\n";
        std::swap(userName, other.userName);
        std::swap(password, other.password);
        std::swap(email, other.email);
        return *this;
    }
    friend bool operator ==(const User &c1, const string &e);



    string getUserName()const;
    string getPassword()const;
    string getEmail()const;

    ~User();
};

为检查是否等于而创建的运算符:

bool operator==(const User & c1, const string& e )
{
    return (c1.email == e);

}

而这个方法在这里我试图在向量中找到实际的电子邮件:

bool checkIfUserExists(vector<User> v,string email, string password) {/* using c++11 lamba expression to find an 
                                                                      element in vector matching my string object 
                                                                      */
    vector<User>::iterator it = std::find_if(v.begin(), v.end(), [&email](const User&c1) {return c1.getEmail == email; });

        if (it != v.end())
        {
            return true;
        }
        else {
            return false;
        }
}

我做错了什么。请我在这方面需要帮助。很快就会哭。提前谢谢你

【问题讨论】:

  • checkIfUserExists 没有任何问题,除了在 lambda 中你忘记调用 c1.getEmail()。
  • 天哪。不敢相信我没看到
  • 已经看了几个小时了 :(
  • 请注意,您可以使用您定义的operator==,如此简单:it = std::find(v.begin(), v.end(), email) !!!

标签: c++ c++11 vector lambda comparison


【解决方案1】:
{return c1.getEmail == email;}

getEmail() 是类方法,而不是类成员。正确的语法应该是:

{return c1.getEmail() == email;}

【讨论】:

  • 天哪。现在要从屋顶上跳下来。哈哈
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 2013-08-17
  • 2012-12-19
  • 2017-11-23
  • 1970-01-01
  • 2015-09-28
  • 2021-09-06
  • 1970-01-01
相关资源
最近更新 更多