c++ map指针 替换元素
在C++中,可以使用std::map容器来存储键值对。如果想要替换map中的元素,可以通过迭代器来访问和修改元素。以下是一个示例代码:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "One";
myMap[2] = "Two";
myMap[3] = "Three";
// 使用迭代器遍历map
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
// 替换map中的元素
auto it = myMap.find(2);
if (it != myMap.end()) {
it->second = "New Two";
}
std::cout << std::endl;
// 再次遍历map,查看替换后的结果
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
return 0;
}
输出结果为:
1: One
2: Two
3: Three
1: One
2: New Two
3: Three
在上述示例中,我们首先创建了一个std::map<int, std::string>对象,并添加了一些键值对。然后,我们使用迭代器遍历了map,并输出了每个键值对的内容。
接下来,我们使用find函数来查找键为2的元素,并将其值替换为"New Two"。然后,我们再次使用迭代器遍历map,并输出替换后的结果。
请注意,如果要替换map中的元素,可以使用迭代器的second成员变量来访问和修改值
原文地址: http://www.cveoy.top/t/topic/ib9A 著作权归作者所有。请勿转载和采集!