如何将Lambda表达式与自定义类对象一起使用

时间:2019-04-03 14:25:03

标签: c++

尝试在STL :: find中使用Lambda表达式在矢量中定位特定对象

我已经基于几个示例编写了代码,并尝试了Lambda,捕获等的许多不同变体。我为类重载了'=='运算符(不确定在这种情况下是否需要这样做,因为我实际上不是在比较对象,而是将object.property与object.property)

//MAIN.cpp

#include <iostream>
#include <vector>
#include <algorithm>
#include "Employee.h"
using namespace std;

int main()
{
    std::vector<Employee> staff
    {
        { "Kate", "Gregory", 1000 },
        { "Obvious", "Artificial", 2000 },
        { "Fake", "Name", 1000 },
        { "Alan", "Turing", 2000 },
        { "Grace", "Hopper", 2000 },
        { "Anita", "Borg", 2000 }
    };

    auto v3 = staff;
    sort(begin(v3), end(v3));

    string searchName = "Hopper";
    auto result = find(begin(staff), end(staff), [searchName](Employee e)->bool {return e.firstname == searchName; });

    return 0;
}


//EMPLOYEE CLASS (in Employee.h)
#pragma once
#include <string>

class Employee
{
public:
    Employee(std::string first, std::string last, int sal) :
        firstname(first), lastname(last), salary(sal) {}

    int getSalary() { return salary; }
    std::string getSortingName() { return lastname + ", " + firstname; }

    std::string firstname;
    std::string lastname;
    int salary;

    bool operator < (const Employee& other)
    {
        if (lastname < other.lastname)
            return true;
        else
            return false;
    }

    bool operator == (Employee other)
    {
        if (lastname == other.lastname &&
            firstname == other.firstname &&
            salary == other.salary)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};

编译时,出现以下错误代码:

错误C2678二进制'==':找不到使用'Employee'类型的左操作数的运算符(或者没有可接受的转换)

studio \ 2017 \ community \ vc \ tools \ msvc \ 14.16.27023 \ include \ xutility 3520

几乎不管我做什么,我都会遇到同样的错误。我唯一能打败它的方法是注释掉失败的行...以“ auto result = find ...”开头的

1 个答案:

答案 0 :(得分:9)

我认为您使用的是错误的功能。根据{{​​3}},find具有恒定值作为第三个参数,而find_if具有UnaryPredicate,这是您要达到的目标。

使用find_if进行更改,它将编译。