// ===== CodeLab: C++11/14/17 新特性 =====
// 来源: https://aoerliang.dpdns.org/articles/cpp-modern
// 以下代码片段按文章出现顺序拼接, 共 6 段

// ----- 片段 1 (cpp) -----
auto i = 42;                  // int
auto d = 3.14;                // double
auto it = m.find("key");      // map<string,int>::iterator

// decltype:不求值,只取类型
decltype(d) x = 1.5;          // x 是 double

// C++14:函数返回类型可以写 auto
auto square(double x) { return x * x; }

// ----- 片段 2 (cpp) -----
vector<int> v = {1, 2, 3, 4, 5};
for (int x : v) { cout << x; }        // 只读
for (int& x : v) { x *= 2; }          // 原地翻倍
for (const auto& item : scores) {     // 只读 + 省拷贝
    cout << item.first;
}

// ----- 片段 3 (cpp) -----
vector<int> v = {3, 1, 4, 1, 5, 9};

sort(v.begin(), v.end(),
     [](int a, int b) { return a > b; });   // 降序

int threshold = 4;
int cnt = count_if(v.begin(), v.end(),
                   [threshold](int x) { return x > threshold; });
// [=] 按值捕获全部,[&] 按引用捕获全部

// ----- 片段 4 (cpp) -----
class Buffer {
    char* data;
public:
    // 移动构造函数:接管对方的资源,把对方置空
    Buffer(Buffer&& other) noexcept
        : data(other.data) {
        other.data = nullptr;
    }
};

vector<string> v;
string big = string(1000000, 'x');
v.push_back(std::move(big));   // 移动而非拷贝,big 变空

// ----- 片段 5 (cpp) -----
int* p = nullptr;        // 取代 NULL,类型安全

// 强类型枚举:不会污染外层作用域,不可隐式转 int
enum class Color { Red, Green, Blue };
Color c = Color::Red;
// if (c == 0) 编译错误,必须 Color::Red

// ----- 片段 6 (cpp) -----
map<string, int> scores = {{"Alice", 95}, {"Bob", 88}};
for (const auto& [name, score] : scores) {
    cout << name << ": " << score << endl;
}

// if 初始化:作用域限定在 if 内
if (auto it = scores.find("Alice"); it != scores.end()) {
    cout << "找到了 " << it->second;
}   // it 在这里已经失效
