C++ Vector of Object searching for which object contains a specific last name 错误 C2678 二进制“==”:未找到运算符

C++ Vector of Object searching for which object contains a specific last name error C2678 binary '==': no operator found

C++ 不是我的技能,所以我有对象向量,它显然是 class.

的几个副本

我的 class 名为“Contact”,我的函数 属性 传入我的矢量对象作为参考。

我一尝试添加这个find,我就猜错了

void Contact::searchContactByLastName(string name, vector<Contact>& allContacts) {

    cout << "In SearchContactByLastName \n";  // 

    unsigned int count = allContacts.size();

    for (unsigned int i = 0; i < count; i++) {
        
        //this works 
        cout << " Last Name " << i << " = " << allContacts[i].getLastName() << endl;
        // THIS IS WHAT DOES NOT WORK, even outside the for loop ....
        if (std::find(allContacts.begin(), allContacts.end(), name) != allContacts.end()) {
            // Found the item
        }
    }


}

因为您可能不想实现 == 运算符来匹配 Contractstd::string,所以 std::find_if 允许您通过匹配功能作为参数。

if (std::find_if(allContacts.begin(), allContacts.end(), [&name](Contract const& contract) {return name == contract.getLastName();}) != allContacts.end()) {
    // Found the item
}