C++中的MAP是一种关联容器,它存储了一对一的键值对。下面是一个使用C++中的MAP的示例代码:
#include <iostream>
#include <map>
int main() {
// 创建一个空的map对象
std::map<std::string, int> map;
// 向map中插入键值对
map["apple"] = 10;
map["banana"] = 20;
map["orange"] = 15;
// 使用迭代器遍历map中的键值对
std::map<std::string, int>::iterator it;
for (it = map.begin(); it != map.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
// 根据键查找对应的值
std::string key = "banana";
if (map.find(key) != map.end()) {
int value = map[key];
std::cout << "Value of key " << key << ": " << value << std::endl;
} else {
std::cout << "Key " << key << " not found in the map." << std::endl;
}
return 0;
}
这段代码展示了如何创建一个空的map对象,插入键值对,遍历map中的键值对,并根据给定的键查找对应的值。
3802

被折叠的 条评论
为什么被折叠?



