STL--map

1.用法举例:

#include <iostream>
#include <map>
using namespace std;

//创建和初始化
map<int, string> myMap =
{
    {1, "one"},
    {2, "two"},
    {3, "three"}
};

//插入元素
// 使用.insert()方法
myMap.insert(pair<int,string>(4, "four"));

// 使用[]操作符
myMap[5] = "five";

// 使用emplace()方法
myMap.emplace(6, "six");

//查找元素
// 使用.find()方法
auto it = myMap.find(2);
if (it != myMap.end())
{
    cout << "Found: " << it->first << " -> " << it->second << endl;
}
else
{
    cout << "Not found" << endl;
}

// 使用.at()方法
try
{
    cout << "Value: " << myMap.at(3) << endl;
}
catch (const out_of_range& e)
{
    cout << "Out of range" <<endl;
}

//访问元素
// 使用[]操作符
cout << "Value: " << myMap[1] << endl;

// 使用迭代器
for (const auto& pair : myMap) {
    cout << pair.first << " -> " << pair.second <<endl;
}

//检查元素
// 使用[]操作符
cout << "Value: " << myMap[1] <endl;

// 使用迭代器
for (const auto& pair : myMap) {
    cout << pair.first << " -> " << pair.second << endl;
}

// 获取大小
cout << "Size: " << myMap.size() << endl;

// 检查是否为空
if (myMap.empty()) {
    cout << "Map is empty" <<endl;
} else {
    cout << "Map is not empty" << endl;
}

map<int, string, greater<int>> myMap({//按照键的降序排列
    {1, "one"},
    {2, "two"},
    {3, "three"}
});

2.输入每种商品的价格,输出每类商品的总价格

#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
class Supermarket
{
private:
    map<string, double> totalValues;//声名名为 的map对象

public:
    // 添加商品和价格
    void addProduct(const string& category, double price)
    {
        totalValues[category] += price;
    }
    // 输出每类商品的总价值
    void displayTotalValues() const
    {
        for (const auto& pair : totalValues)
        {
            cout << "类别: " << pair.first << ", 总价值: " << pair.second << endl;
        }
    }
};

int main()
{
    // 创建超市对象
    Supermarket supermarket;

    // 添加商品和价格
    supermarket.addProduct("水果", 5.5);
    supermarket.addProduct("水果", 3.2);
    supermarket.addProduct("蔬菜", 2.3);
    supermarket.addProduct("饮料", 4.0);
    supermarket.addProduct("水果", 6.0);
    supermarket.addProduct("饮料", 3.5);
    supermarket.addProduct("蔬菜", 1.8);

    // 输出每类商品的总价值
    supermarket.displayTotalValues();

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值