We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
确保多线程下输出顺序和输入顺序保持一致,因为输入和输出并不同时进行,所以不用加锁。进行记录输入顺序。
#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; }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
确保多线程下输出顺序和输入顺序保持一致,因为输入和输出并不同时进行,所以不用加锁。进行记录输入顺序。
The text was updated successfully, but these errors were encountered: