// ===== CodeLab: C++11 新特性实战:auto、lambda、智能指针与移动语义 =====
// 来源: https://aoerliang.dpdns.org/articles/cpp11-features
// 以下代码片段按文章出现顺序拼接, 共 5 段

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

int main() {
    std::map<std::string, int> scores;
    scores["Alice"] = 95;

    // 以前要写:std::map<std::string,int>::iterator it = scores.begin();
    auto it = scores.begin();
    std::cout << it->first << ": " << it->second << std::endl;

    auto sum = 0;                      // 推导为 int
    auto pi = 3.14;                    // 推导为 double
    auto name = std::string("Bob");    // 推导为 std::string
    std::cout << sum << " " << pi << " " << name << std::endl;
    return 0;
}

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

int main() {
    std::vector<int> v = {5, 2, 8, 1, 9};

    // 降序排序:lambda 直接写在调用处
    std::sort(v.begin(), v.end(),
              [](int a, int b) { return a > b; });

    // [threshold] 按值捕获外部变量
    int threshold = 5;
    int big = std::count_if(v.begin(), v.end(),
                            [threshold](int x) { return x > threshold; });

    auto print = [](int x) { std::cout << x << ' '; };
    std::for_each(v.begin(), v.end(), print);
    std::cout << std::endl;
    std::cout << "大于 " << threshold << " 的有 " << big << " 个" << std::endl;
    return 0;
}

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

struct Point {
    int x, y;
    Point(int a, int b) : x(a), y(b) {}
};

void print(const Point& p) {
    std::cout << p.x << ", " << p.y << std::endl;
}

int main() {
    // unique_ptr:独占,不允许拷贝
    std::unique_ptr<Point> p(new Point(3, 4));
    print(*p);

    // shared_ptr:共享,引用计数
    std::shared_ptr<Point> q = std::make_shared<Point>(1, 2);
    std::shared_ptr<Point> r = q;        // 计数变为 2
    print(*r);

    // 离开作用域自动释放,无需手动 delete
    return 0;
}

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

class Buffer {
public:
    explicit Buffer(std::size_t n)
        : size_(n), data_(new char[n]) {}

    // 移动构造函数:偷走对方的资源
    Buffer(Buffer&& other) noexcept
        : size_(other.size_), data_(other.data_) {
        other.data_ = nullptr;
        other.size_ = 0;
    }

    // 移动赋值
    Buffer& operator=(Buffer&& other) noexcept {
        if (this != &other) {
            delete[] data_;
            size_ = other.size_;
            data_ = other.data_;
            other.data_ = nullptr;
            other.size_ = 0;
        }
        return *this;
    }

    ~Buffer() { delete[] data_; }

private:
    std::size_t size_;
    char* data_;
};

int main() {
    std::vector<std::string> lines;
    std::string line = "hello world";
    lines.push_back(std::move(line));  // 搬进去,不再深拷贝
    std::cout << lines[0] << std::endl;
    return 0;
}

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

# 也可以使用 clang
clang++ -std=c++11 main.cpp -o main
