代码拉取完成,页面将自动刷新
#include <atomic>
#include <iostream>
#include <mutex>
#include <unordered_map>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
class ShoppingCart {
private:
ShoppingCart() = default;
public:
~ShoppingCart() = default;
ShoppingCart(ShoppingCart const &other) = delete;
ShoppingCart(ShoppingCart const &&other) = delete;
ShoppingCart &operator=(ShoppingCart const &other) = delete;
ShoppingCart &operator=(ShoppingCart const &&other) = delete;
static ShoppingCart *GetInstance() {
ShoppingCart *cart = mAtomic.load();
if (cart == nullptr) {
std::unique_lock<std::mutex> lock(mMutex);
cart = mAtomic.load();
if (cart == nullptr) {
cart = new ShoppingCart;
mAtomic.store(cart);
}
}
return cart;
}
void addItem(std::string item, int cnt) {
if (item.empty() or cnt <= 0)
return;
order.push_back(item);
items[item] += cnt;
}
void showItem() {
for (std::string const &item : order) {
cout << item << " " << items[item] << endl;
}
}
private:
std::unordered_map<std::string, int> items; // 保存购物车物品和数量
std::vector<std::string> order; // 保证购物车物品顺序
static std::mutex mMutex; // 保证线程安全
static std::atomic<ShoppingCart *> mAtomic; // 保证线程安全
};
std::atomic<ShoppingCart *> ShoppingCart::mAtomic;
std::mutex ShoppingCart::mMutex;
int main() {
int cnt;
std::string name;
while (cin >> name >> cnt) {
ShoppingCart::GetInstance()->addItem(name, cnt);
}
ShoppingCart::GetInstance()->showItem();
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。