// ===== CodeLab: C++17 新特性:结构化绑定、if constexpr 与 std::optional =====
// 来源: https://aoerliang.dpdns.org/articles/cpp17-features
// 以下代码片段按文章出现顺序拼接, 共 5 段

// ----- 片段 1 (cpp) -----
#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> scores = {
        {"Alice", 95}, {"Bob", 87}, {"Carol", 92}
    };

    // 遍历 map:直接拿到名字和分数
    for (const auto& [name, score] : scores) {
        std::cout << name << ": " << score << std::endl;
    }

    // insert 的返回值(pair 迭代器和 bool)也能拆
    auto [it, inserted] = scores.insert({"Dave", 88});
    if (inserted) {
        std::cout << "插入成功: " << it->first << std::endl;
    }
    return 0;
}

// ----- 片段 2 (cpp) -----
#include <iostream>
#include <type_traits>

template <typename T>
void inspect(const T& value) {
    if constexpr (std::is_integral_v<T>) {
        std::cout << "整型,值 = " << value << std::endl;
    } else if constexpr (std::is_floating_point_v<T>) {
        std::cout << "浮点,值 = " << value << std::endl;
    } else {
        std::cout << "其他类型" << std::endl;
    }
}

int main() {
    inspect(42);      // 整型
    inspect(3.14);    // 浮点
    inspect("hi");    // 其他类型
    return 0;
}

// ----- 片段 3 (cpp) -----
#include <iostream>
#include <optional>
#include <string>

// 按 id 查名字,查不到返回 nullopt
std::optional<std::string> find_name(int id) {
    if (id == 1) return "Alice";
    if (id == 2) return "Bob";
    return std::nullopt;   // 显式表示"没有值"
}

int main() {
    auto name = find_name(2);
    if (name) {                        // 隐式转换为 bool
        std::cout << "找到: " << *name << std::endl;
    } else {
        std::cout << "未找到" << std::endl;
    }
    // 带默认值的访问,一行搞定
    std::cout << find_name(99).value_or("unknown") << std::endl;
    return 0;
}

// ----- 片段 4 (cpp) -----
#include <iostream>
#include <map>
#include <string>
#include <string_view>

int main() {
    std::map<std::string, int> m = {{"a", 1}, {"b", 2}};

    // if 初始化语句:条件里多一个局部变量,作用域更小
    if (auto it = m.find("a"); it != m.end()) {
        std::cout << "找到 a = " << it->second << std::endl;
    }

    // string_view:不拷贝,只"看"底层字符
    std::string s = "hello";
    std::string_view view = s;
    s[0] = 'H';
    std::cout << view << std::endl;   // 输出 Hello
    return 0;
}

// ----- 片段 5 (cpp) -----
# 编译并运行
g++ -std=c++17 main.cpp -o main
./main

clang++ -std=c++17 main.cpp -o main
