Skip to content

单例模式:c++代码懒加载无法通过 #4

Description

@Cupcc

确保多线程下输出顺序和输入顺序保持一致,因为输入和输出并不同时进行,所以不用加锁。进行记录输入顺序。

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

class ShoppingCartManager {
private:
    // Stores the order of item insertion
    std::vector<std::string> order;

    // Maps item names to their quantities
    std::unordered_map<std::string, int> cart;

    // Private constructor for Singleton
    ShoppingCartManager() {}

    // Deleted copy constructor and assignment operator for Singleton
    ShoppingCartManager(const ShoppingCartManager&) = delete;
    ShoppingCartManager& operator=(const ShoppingCartManager&) = delete;

public:
    // Method to get the Singleton instance
    static ShoppingCartManager& getInstance() {
        static ShoppingCartManager instance;
        return instance;
    }

    // Method to add items to the cart
    void addToCart(const std::string& itemName, int quantity) {
       if (cart.find(itemName) == cart.end()){
           order.emplace_back(itemName);
       }
       cart[itemName] += quantity; 
    }

    // Method to view the cart
    void viewCart() {
        for (const auto& itemName : order) {
            std::cout << itemName << " " << cart[itemName] << std::endl;
        }
    }
};

int main() {
    ShoppingCartManager& cart = ShoppingCartManager::getInstance();
    std::string itemName;
    int quantity;

    // Reading items until end-of-file or error
    while (std::cin >> itemName >> quantity) {
        cart.addToCart(itemName, quantity);
    }

    // Output cart contents
    cart.viewCart();

    return 0;
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions