lambda 表达式简单使用

lambda 表达式简单使用

在开发中常常会用到 C++11 中的 lambda 表达式,其结合 STL 可让代码更简洁明了。

简单示例代码如下:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<std::string> strLst = {"a", "ab", "abc", "abcd", "abcde", "fghi", "fgh", "fg", "f"};

    std::for_each(strLst.cbegin(), strLst.cend(), [](const std::string& str) { 
        std::cout << str << std::endl; 
    });

    auto compStrSize = [](const std::string& str1, const std::string& str2) -> bool {
        return str1.size() < str2.size();
    };
    const std::string& maxSizeStr = *std::max_element(strLst.cbegin(), strLst.cend(), compStrSize);
    std::cout << "\nmax size str: " << maxSizeStr << std::endl;
    
    return 0;
}

终端输出:

a
ab
abc
abcd
abcde
fghi
fgh
fg
f

max size str: abcde

通过上述代码可知,使用 lambda 表达式不仅简明地表达了所需功能,还让代码更加紧凑,无需另外定义一个函数;

本文仅展示了 lambda 表达式的简单使用,关于其详细介绍,参考任一包含 C++11 标准的教材即可;


本文作者: 王同学