c++ - 谁能给我解释一下 [](int i){ return i % 2 == 0; } 方法?

标签 c++ algorithm stl

<分区>

在下面STL算法的示例代码中std::all_of,

什么是'[](int i){ return i % 2 == 0; }'是什么意思?

int main() { 

    std::vector<int> v{10, 2, 4, 6}; 

    if (std::all_of(v.begin(), v.end(), [](int i){ return i % 2 == 0; })) { 
        std::cout << "All numbers are even\n"; 
    } 
    else{
        std::cout << "All numbers are not even\n"; 
    }
}

最佳答案

这是一个lambda function检查 i 是否偶数。如果 i 是偶数,它将返回 true,否则返回 false。

它的逻辑等同于:

#include <algorithm>
#include <iostream>

bool isEven(int i) {
  return i % 2 == 0;
}

int main() { 

    std::vector<int> v{10, 2, 4, 6}; 

    if (std::all_of(v.begin(), v.end(), isEven)) { 
        std::cout << "All numbers are even\n"; 
    } 
    else{
        std::cout << "All numbers are not even\n"; 
    }
}

输出:

All numbers are even


注意:这是 lambda 方法是一个自由函数,它捕获任何东西。

PS:那个lambda方法与STL无关。

关于c++ - 谁能给我解释一下 [](int i){ return i % 2 == 0; } 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57348260/

相关文章:

c++ - 从在 postgresql 上运行的 C++ 文件打印

c++ - 文字和 constexpr 函数,编译时评估

c++ - 哪些情况会导致 clock() 返回 -1(即失败)?

multithreading - 如何在 python 中处理大文件?

C++ valgrind 可能在 STL 字符串上泄漏

std::map::at() 的 C++98 包装器

c++ - 如何在我指向的andress上动态分配内存?

c# - 确定字符串是否为合法 XML 元素名称的有效方法

ios - 围绕中心质量创建圆形路径的算法?

c++ - gcc reverse_iterator 比较运算符丢失了吗?