C++ 入门第23天:Lambda 表达式与标准库算法入门

往期回顾:

C++ 入门第 20 天:STL 容器之无序集合与无序多重集合-优快云博客

C++ 入门第 21 天:STL 容器之无序映射与无序多重映射-优快云博客

C++ 学习第22天:智能指针与异常处理-优快云博客


 C++ 入门第23天:Lambda 表达式与标准库算法入门

前言

今天我们学习两个重要的 C++ 特性:Lambda 表达式标准库中的算法。这两个特性是现代 C++ 编程的重要组成部分,能让我们的代码更简洁、高效。


1. Lambda 表达式

1.1 什么是 Lambda 表达式?

Lambda 表达式是 C++11 引入的一种匿名函数,用于简化代码。它允许我们直接在需要的地方定义函数,而不需要单独声明或定义。

1.2 Lambda 表达式的语法

Lambda 表达式的基本语法如下:

[capture](parameters) -> return_type {
    // 函数体
};

其中: 

  • [capture]:捕获列表,定义 Lambda 可以使用的外部变量。
  • (parameters):参数列表,类似普通函数的参数。
  • -> return_type:返回类型,可选。如果可以推导返回类型,可以省略。
  • {}:函数体,包含要执行的代码。

1.3 Lambda 表达式示例

#include <iostream>
using namespace std;

int main() {
    // 简单的 Lambda 表达式
    auto add = [](int a, int b) -> int {
        return a + b;
    };

    cout << "3 + 5 = " << add(3, 5) << endl;

    // 无参数的 Lambda 表达式
    auto greet = []() {
        cout << "Hello, Lambda!" << endl;
    };

    greet();

    return 0;
}

输出结果

3 + 5 = 8 
Hello, Lambda! 

1.4 捕获列表的用法

Lambda 表达式可以通过捕获列表访问外部变量:

#include <iostream>
using namespace std;

int main() {
    int x = 10;
    int y = 20;

    // 捕获 x 和 y
    auto sum = [x, y]() {
        return x + y;
    };

    cout << "x + y = " << sum() << endl;

    // 捕获所有变量的引用
    auto increment = [&]() {
        x++;
        y++;
    };

    increment();
    cout << "After increment, x = " << x << ", y = " << y << endl;

    return 0;
}

输出结果

x + y = 30 After increment, x = 11, y = 21


2. 标准库算法

2.1 什么是标准库算法?

C++ 的标准库算法头文件 <algorithm> 提供了一组常用的算法函数,用于处理容器中的数据,例如排序、查找、遍历等。

2.2 常用算法函数

以下是一些常用的标准库算法:

  1. std::sort:排序。
  2. std::find:查找元素。
  3. std::for_each:对容器中的每个元素执行操作。
  4. std::count:统计特定值的出现次数。
  5. std::accumulate:计算容器中所有元素的累计和(需要 <numeric> 头文件)。

2.3 示例代码

2.3.1 使用 std::sort
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> numbers = {5, 2, 9, 1, 5, 6};

    // 对容器排序
    sort(numbers.begin(), numbers.end());

    cout << "Sorted numbers: ";
    for (int n : numbers) {
        cout << n << " ";
    }
    cout << endl;

    return 0;
}

输出结果

Sorted numbers: 1 2 5 5 6 9 
2.3.2 使用 std::find
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> numbers = {5, 2, 9, 1, 5, 6};

    // 查找元素 9
    auto it = find(numbers.begin(), numbers.end(), 9);

    if (it != numbers.end()) {
        cout << "Found 9 at index: " << distance(numbers.begin(), it) << endl;
    } else {
        cout << "9 not found" << endl;
    }

    return 0;
}

输出结果

Found 9 at index: 2 
2.3.3 使用 std::for_each
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> numbers = {1, 2, 3, 4, 5};

    // 遍历容器并打印每个元素
    for_each(numbers.begin(), numbers.end(), [](int n) {
        cout << n * n << " ";  // 打印平方
    });

    cout << endl;
    return 0;
}

输出结果

1 4 9 16 25

2.3.4 使用 std::count
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> numbers = {1, 2, 3, 1, 1, 4, 1};

    // 统计元素 1 的出现次数
    int count_of_ones = count(numbers.begin(), numbers.end(), 1);

    cout << "Count of 1: " << count_of_ones << endl;

    return 0;
}

输出结果

Count of 1: 4 
2.3.5 使用 std::accumulate
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int main() {
    vector<int> numbers = {1, 2, 3, 4, 5};

    // 计算累计和
    int total = accumulate(numbers.begin(), numbers.end(), 0);

    cout << "Total sum: " << total << endl;

    return 0;
}

输出结果

Total sum: 15 

结语

以上就是 C++ 中的 Lambda 表达式标准库算法的基础知识点了。Lambda 表达式 是一种简化代码的方法,特别适合在算法函数中使用。标准库算法 提供了多种容器操作工具,可以大幅减少代码量,提高开发效率。理解它们的特性和使用方法,可以显著提升我们的代码效率。编写更加简洁、优雅的 C++ 程序。

都看到这里了,点个赞再走呗朋友~

加油吧,预祝大家变得更强!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值