一个能被接手的小工程

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

(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)⚠️ 判题机只编一个源文件,所以这条路线的"多文件工程"**都用注释分段的方式写在一个文件里**——分段的**顺序和依赖关系是真的**,只是没有真的分成几个文件。三段:声明、实现、测试。

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

/* ── 相当于 basket.h:只说有什么 ── */
class BadQty : public std::invalid_argument {
public:
    explicit BadQty(const std::string &w) : std::invalid_argument(w) {}
};

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);
    int kinds() const;
    int total() const;
    int many(int line) const;
private:
    std::vector<std::unique_ptr<Item>> items_;
};

/* ── 相当于 basket.cpp:怎么做写在这儿 ── */
void Basket::add(std::string name, int qty) {
    if (qty <= 0) throw BadQty(name);
    items_.push_back(std::make_unique<Item>(std::move(name), qty));
}
int Basket::kinds() const { return static_cast<int>(items_.size()); }
int Basket::total() const {
    return std::accumulate(items_.begin(), items_.end(), 0,
        [](int s, const std::unique_ptr<Item> &p) { return s + p->qty; });
}
int Basket::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; }));
}

/* ── 相当于 test.cpp:接手第一件事,把测试跑一遍 ── */
static int ran = 0, passed = 0;
#define CHECK(cond) do { ran++; if (cond) passed++; } while (0)

int main() {
    int owed = 0;
    {
        Basket b;
        b.add("apple", 3);
        b.add("pear", 5);
        b.add("fig", 2);

        int rejected = 0;
        try { b.add("plum", 0); } catch (const BadQty &) { rejected = 1; }

        CHECK(b.kinds() == 3);
        CHECK(b.total() == 10);
        CHECK(b.many(2) == 2);
        CHECK(rejected == 1);
    }
    owed = Item::made - Item::gone;

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

                        
👩‍🏫
AI
💬 题目评论

全部评论