linux c++的map的返回值给出例子
在C++中,std::map是一个关联容器,它提供了一种将键与值相关联的方式。std::map中的operator[]可以用来访问和修改键对应的值。
std::map的operator[]返回一个引用,可以用于读取和修改值。如果键不存在,则会自动插入一个新的键值对。
下面是一个使用std::map的例子:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
// 插入键值对
myMap[1] = "One";
myMap[2] = "Two";
myMap[3] = "Three";
// 访问和修改值
std::cout << myMap[1] << std::endl; // 输出: One
myMap[2] = "New Two";
std::cout << myMap[2] << std::endl; // 输出: New Two
// 检查键是否存在
if (myMap.find(3) != myMap.end()) {
std::cout << "Key 3 exists" << std::endl;
}
// 遍历键值对
for (const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
在上面的例子中,我们创建了一个std::map对象myMap,并插入了三个键值对。然后,我们使用operator[]访问和修改值,并使用find函数检查键是否存在。最后,我们使用范围for循环遍历了键值对并输出了它们的值
原文地址: https://www.cveoy.top/t/topic/iD8g 著作权归作者所有。请勿转载和采集!