一个完整的小程序跑一遍
(本条路线统一用 g++ -std=c++17 -O0 -Wall 编译)类 + map,带一条输入检查:
#include <iostream>
#include <map>
#include <string>
#include <vector>
class Basket {
public:
void add(const std::string &name, int qty) {
if (qty <= 0) { bad_++; return; }
items_[name] += qty;
}
int kinds() const { return static_cast<int>(items_.size()); }
int total() const {
int s = 0;
for (const auto &kv : items_) s += kv.second;
return s;
}
int bad() const { return bad_; }
int qty_of(const std::string &name) const {
auto it = items_.find(name); /* find 不会插进去 */
return (it == items_.end()) ? 0 : it->second;
}
private:
std::map<std::string, int> items_;
int bad_ = 0;
};
int main() {
Basket b;
b.add("apple", 3);
b.add("pear", 5);
b.add("apple", 2); /* 同一种,累加 */
b.add("plum", 0); /* 不合格,记一笔 */
std::cout << b.kinds() << "/" << b.total() << "/" << b.qty_of("apple")
<< "/" << b.qty_of("nothing") << "/" << b.bad() << "\n";
return 0;
}
全部评论