一段完整的现代 C++ 跑一遍

👁️ 1 人浏览 💬 0 人评论 ❤️ 添加收藏

(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)类 + 智能指针 + STL 算法 + 一条输入检查:

#include <iostream>
#include <memory>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
#include <stdexcept>

struct Item {
    static int made, gone;
    std::string name;
    int qty;
    Item(std::string n, int q) : name(std::move(n)), qty(q) { made++; }
    ~Item() { gone++; }
};
int Item::made = 0;
int Item::gone = 0;

class Basket {
public:
    void add(std::string name, int qty) {
        if (qty <= 0) { bad_++; return; }
        items_.push_back(std::make_unique<Item>(std::move(name), qty));
    }
    int kinds() const { return static_cast<int>(items_.size()); }
    int total() const {
        return std::accumulate(items_.begin(), items_.end(), 0,
            [](int s, const std::unique_ptr<Item> &p) { return s + p->qty; });
    }
    int many(int line) const {
        return static_cast<int>(std::count_if(items_.begin(), items_.end(),
            [line](const std::unique_ptr<Item> &p) { return p->qty > line; }));
    }
    int bad() const { return bad_; }

private:
    std::vector<std::unique_ptr<Item>> items_;
    int bad_ = 0;
};

int main() {
    int owed = 0;
    {
        Basket b;
        b.add("apple", 3);
        b.add("pear", 5);
        b.add("fig", 2);
        b.add("plum", 0);            /* 不合格 */

        std::cout << b.kinds() << "/" << b.total() << "/" << b.many(2)
                  << "/" << b.bad();
    }
    owed = Item::made - Item::gone;  /* 出了大括号,全都还清了 */

    std::cout << "/" << owed << "\n";
    return 0;
}
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论