Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Cupcc opened this issue Jan 17, 2024 · 0 comments
Open

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

Cupcc opened this issue Jan 17, 2024 · 0 comments

Comments

@Cupcc
Copy link

Cupcc commented Jan 17, 2024

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

#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant