c++ - find_if 中具有多个参数的 Lambda

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

我有一个包含自定义数据类型对象的 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/

相关文章:

algorithm - 在动态数组的前 N ​​个元素中查找最大元素

java - 查找多维数组的所有垂直遍历

c++ - 将数组追加到 vector 中

c++ - 编译和链接项目时 Visual Studio 2015 挂起

c++ - stringstream 的重复输出

c++ - GCC 生成不需要的汇编代码

c++ - 使用iterator和reverse_iterator打印 vector 元素有没有更好的方法?

c++ - 使用 Visual Studio 将 HTML 浏览器嵌入到 native C++/Win32 项目中

c# - 解释我从 OrderBy 的性能测试中得到的以下结果

c++ - 是否可以将大括号括起来的初始化程序作为宏参数传递?