我有一个vector
课程。每个类都有两个成员变量,一个名称(字符串)和工作时间(整数)。我的目标只是删除数组中包含特定名称的元素。
我知道我无法使用该find()
算法,所以我正在尝试使用该find_if()
算法。我尝试过创建自己的布尔函数,但它不起作用。所以我尝试使用 lambda 函数,结果同样不好。
阅读 的文档find_if
。显然我需要给它一个可调用的对象,比如指针。但如果是这样,我将如何通过我的Employee
类,比较name
它的成员函数以及我想要与它进行比较的单词?
这是我的代码:
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <string_view>
#include <string>
//First problem is using class and std::vector
//Track employees and time worked
class Employee
{
public:
std::string_view m_name{};
int m_time{};
Employee(std::string_view name, int time)
:m_name{name}, m_time {time}
{
}
};
void printEmployees(const std::vector<Employee>& employee)
{
for (const auto& a: employee)
{
std::cout << a.m_name << " " << a.m_time << "\n";
}
}
bool findEmployee(Employee &employee, std::string_view myWord)
{
if (myWord == employee.m_name)
return true;
else
return false;
}
int main()
{
std::vector<Employee> employee{ {"Daniel Ramirez", 14},
{"Marta Martinez", 55},
{"Joseph Martin", 100}
};
// erase the element that contains "Marta Martinez" on the array:
std::string myWord{"Marta Martinez"};
// auto it { std::find_if(employee.begin(),employee.end(), findEmployee(employee, myWord) ) };
//using lambda
auto it { std::find_if(employee.begin(),employee.end(), [](const Employee& employee, std::string_view myWord)
{
if (myWord == employee.m_name)
return true;
else
return false;
}) };
if (it == employee.end()) // check if element was found
std::cout << "Element wasn't found";
//printEmployees(employee);
return 0;
}
错误:
error: no matching function for call to object of type '(lambda at /Users/danielramirez/CLionProjects/test/main.cpp:81:63)'
if (__pred(*__first))
我知道我在实现算法的第三个参数方面做错了find_if
。非常感谢任何帮助。
find_if
采用单参数 lambda。您不需要传递myWord
给它,您只需捕获它(使用例如[&]
- “默认情况下通过引用捕获所有”)。您还可以简化
if (x) return true; else return false;
为return x;
,如图所示。然后将生成的迭代器传递给
employee.erase(it);
(如果不是.end()
)以删除该元素。或者您可以使用
std::erase_if(employee, /*same lambda as a above*/);
oneliner 删除所有匹配项。