我有一个包含自定义数据类型对象的 vector 。该数据类型的字段之一是枚举。我想确保对于所有枚举值,至少有一个条目添加到 vector 中。
我想使用 std::find_if() 来检查 vector 是否具有某个枚举值的条目。但我不确定如何正确编写和使用 lambda。这是我得到的:
struct CustomType
{
EnumType type {EnumType::DEFAULT};
int x;
};
std::vector<CustomType> tmp;
// fetch values from database and add them to the vector
// for some EnumType values there might not be a record added to the vector
auto hasEnumType = [](const CustomType& customType, const EnumType& enumType) -> bool
{
return (customType.type == enumType);
};
// What do I replace '?' with to get the current position
if (std::find_if(tmp.begin(), tmp.end(), hasEnumType(?, EnumType::VALUE1)) != tmp.end())
{
//add CustomType with VALUE1 to vector
}
最佳答案
如果您想检查固定值,只需将其放入 lambda 中即可。
if ( std::find_if(tmp.begin(), tmp.end(), [](CustomType const & customType)
{ return customType.type == EnumType::VALUE; }) )
{ /* do something */}
如果您想在某种意义上将其作为参数传递给 lambda,您可以将其设置在外部变量中并通过引用“捕获”它
auto enumType = EnumType::VALUE;
// capture variables by references --------V
if ( std::find_if(tmp.begin(), tmp.end(), [&](CustomType const & customType)
{ return customType.type == enumType; }) )
{ /* do something */ }
关于c++ - find_if 中具有多个参数的 Lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49531658/