【问题标题】:Lambda with multiple parameters in find_iffind_if 中具有多个参数的 Lambda
【发布时间】:2018-03-28 10:06:14
【问题描述】:

我有一个带有自定义数据类型对象的向量。此数据类型的字段之一是枚举。我想确保对于所有枚举值,至少将一个条目添加到向量中。

我想使用std::find_if() 检查向量是否有某个枚举值的条目。但我不确定如何正确编写和使用 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
}

【问题讨论】:

    标签: c++ algorithm c++11 lambda find


    【解决方案1】:

    如果你想检查一个固定值,你可以简单地把它放在 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 */ }
    

    【讨论】:

      【解决方案2】:

      std::find_if 将一元谓词作为其第三个参数。如果您提供二进制谓词,它将无法通过类型检查。

      一种方法是通过捕获其中一个参数将二元谓词转换为一元谓词。要为所有 enum 值自动执行此操作,请创建一个返回另一个函数的函数。

      auto getTypeChecker = [](const EnumType enumType)
      {
          return [enumType](const CustomType& customType)
          {
              return (customType.type == enumType);
          };
      };
      

      然后声明一个函数,负责插入向量中不存在的枚举值 -

      void insert_if_not_present(std::vector<CustomType>& vec, const EnumType type)
      {
          if(std::none_of(begin(vec), end(vec), getTypeChecker(type)))
          {
              //add CustomType with type to vec
          }
      }
      

      现在为每个枚举值调用一次insert_if_not_present

      注意,这里为了方便我使用了std::none_of。您可以使用std::find_if 代替std::none_of 以smae 方式。

      【讨论】:

        猜你喜欢
        • 2019-03-28
        • 2017-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多