设计模式第一天|单例模式 1.小明的购物车

目录

【设计模式专题之单例模式】1.小明的购物车

文章链接:卡码网设计模式

题目链接:1.小明的购物车

单例模式:

cpp 复制代码
#include <iostream>
#include <unordered_map>
#include <vector>

using namespace std;

class ShoppingCartManager {
private:
    unordered_map<string, int> cart;
    vector<string> order; // 保持顺序

    // 私有构造函数
    ShoppingCartManager() {}

public:
    // 获取购物车实例
    static ShoppingCartManager& getInstance() {
        static ShoppingCartManager instance;
        return instance;
    }

    // 添加商品
    void addToCart(const string& itemName, int quantity) {
        if (cart.find(itemName) == cart.end()) {
            order.emplace_back(itemName);
        }
        cart[itemName] += quantity; +=和=都行
    }

    // 查看商品
    void viewCart() const {
        for (const auto& itemName : order) {
            cout << itemName << " " << cart.at(itemName) << endl;
        }
    }
};

int main() {
    string itemName;
    int quantity;

    ShoppingCartManager& cart = ShoppingCartManager::getInstance();

    while (cin >> itemName >> quantity) {
        cart.addToCart(itemName, quantity);
    }

    cart.viewCart();

    return 0;
}

这题注意清单输出顺序,map底层是红黑树,unordered_map底层是哈希表,无法保证输出顺序和输入相同,这里创建了一个vector来保证输出顺序,并使用了emplace_back方法,在向量的末尾直接构造一个元素,而不是先创建一个元素对象再将其复制或移动到向量中(push_back)。

另外注意程序中&和const的使用。

设计模式第一天打卡,加油!!!

相关推荐
happyness4420 分钟前
AI编程与设计模式
设计模式·ai编程
就是小王同学啊32 分钟前
Spring小技巧之设计模式
sql·spring·设计模式
Larcher18 小时前
当 AI 学会写代码:一个自动生成 React 项目的 Agent 实战
人工智能·设计模式·程序员
我登哥MVP1 天前
走进 Gang of Four 设计模式:解释器模式
java·设计模式·解释器模式
我登哥MVP1 天前
走进 Gang of Four 设计模式:过滤器模式
java·设计模式·过滤器模式
kisshyshy2 天前
从无崖子到OpenAI:大模型间的“传功”,动了谁的奶酪?
人工智能·深度学习·设计模式
某不知名網友2 天前
C++ 六大常用设计模式详解(单例、工厂、策略、状态、观察者、代理)
开发语言·c++·设计模式
咖啡八杯2 天前
GoF设计模式——责任链模式
设计模式·面试·架构
大辉狼_音频架构3 天前
Vol.01 高频设计模式
设计模式
我登哥MVP3 天前
走进 Gang of Four 设计模式:代理模式
设计模式·代理模式