C++11–C++17 Lambda 表达式面试题集
C++11–C++17 Lambda 表达式面试题集

本文给出一套基于 C++11 至 C++17 的 Lambda 表达式面试题,分为基础理解、STL 应用、底层原理和语言障眼等组成。


🔹 一、基础理解题

Q1. 以下代码的输出是什么?为什么?

1int a = 10;
2auto lambda = [a]() mutable {
3    a += 5;
4    std::cout << a << std::endl;
5};
6lambda();
7std::cout << a << std::endl;

答案:

15
10

Q2. 判断以下语法是否合法?

1int x = 5;
2auto f = [&x, x](int y) {
3    return x + y;
4};

答案:

  • C++11: 不合法

  • C++14+: 合法


Q3. 写出一个保证 counter == 5 的 lambda

 1int counter = 0;
 2std::function<void()> f;
 3
 4{
 5    int temp = 5;
 6    // 在这里定义 lambda
 7    f = [val = temp, &counter]() {
 8        counter = val;
 9    };
10}
11
12f();  // counter == 5

🔹 二、STL 应用题

Q4. 用 Lambda 对字符串数组按长度排序

1std::vector<std::string> vec = {"cat", "elephant", "dog", "antelope"};
2std::sort(vec.begin(), vec.end(), [](const auto& a, const auto& b) {
3    return a.length() < b.length();
4});

Q5. 过滤 vector,保留 >10 元素

1std::vector<int> nums = {3, 12, 7, 18, 5};
2int threshold = 10;
3std::vector<int> result;
4
5std::copy_if(nums.begin(), nums.end(), std::back_inserter(result),
6             [threshold](int x) { return x > threshold; });

🔹 三、底层原理题

Q6. 编译器将下列 lambda 扩展成怎样的类?

1int a = 1, b = 2;
2auto f = [=, &b](int x) {
3    return a + b + x;
4};

类类似实现:

1class Lambda {
2    int a;
3    int& b;
4public:
5    Lambda(int a_, int& b_) : a(a_), b(b_) {}
6    int operator()(int x) const {
7        return a + b + x;
8    }
9};

Q7. 为什么无损损 lambda 可转换为函数指针?

1auto f = [](int x) { return x + 1; };
2int (*fp)(int) = f;  // 正确
3
4int a = 10;
5auto g = [a](int x) { return a + x; };
6// int (*gp)(int) = g;  // 错误

Q8. 泛型 lambda 怎样实现?

1auto f = [](auto x, auto y) { return x + y; };

等价类型编译器扩展:

1struct Lambda {
2    template<typename T1, typename T2>
3    auto operator()(T1 x, T2 y) const {
4        return x + y;
5    }
6};

🔹 四、障眼题 & 扩展

Q9. 是否存在悬排引用?

1std::function<void()> f;
2{
3    int x = 42;
4    f = [&x]() {
5        std::cout << x << std::endl;
6    };
7}
8f(); // 未定行为!

Q10. 此 lambda 的返回类型是否合法?

1auto f = [](bool b) {
2    if (b) return 1;
3    else return 3.14;
4};

错误:返回类型不符合

修复:

1auto f = [](bool b) -> double {
2    return b ? 1 : 3.14;
3};

✅ Bonus: 手写 lambda 行为类

Q11. 手写等价类

1int a = 10, b = 20;
2auto f = [a, &b](int x) { return a + b + x; };

等价类:

1class SimulatedLambda {
2    int a;
3    int& b;
4public:
5    SimulatedLambda(int a_, int& b_) : a(a_), b(b_) {}
6    int operator()(int x) const {
7        return a + b + x;
8    }
9};

最后修改于 2025-05-14 11:35