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;
}