第五节 · 俄罗斯套娃 · 局部类与嵌套类

C++ 持续演进,让我们来看看最新标准中的一些重要特性。


结构化绑定(C++17)

int main()
{
    // 解构 pair
    pair<int, string> p = {42, "hello"};
    auto [num, str] = p;
    cout << num << ", " << str << endl;
    
    // 解构 tuple
    tuple<int, double, string> t = {1, 2.0, "three"};
    auto [a, b, c] = t;
    
    // 解构数组
    int arr[3] = {1, 2, 3};
    auto [x, y, z] = arr;
    
    // 解构结构体
    struct Point { int x, y; };
    Point point = {10, 20};
    auto [px, py] = point;
    
    // 在 for 循环中使用
    map<string, int> m = {{"one", 1}, {"two", 2}};
    for (auto& [key, value] : m)
    {
        cout << key << ": " << value << endl;
    }
    
    return 0;
}

if/switch 初始化(C++17)


三路比较运算符(C++20)


范围 for 循环增强(C++20)


Ranges 库(C++20)


协程(C++20)


模块(C++20)


consteval 和 constinit(C++20)


std::format(C++20)


std::expected(C++23)


更多 C++23 特性


习题

  • 使用 Ranges 库重写一个数据处理管道。

  • 比较模块与头文件的优缺点。

  • 研究协程在异步编程中的应用。

Last updated