C++ 使用指针替换 Map 中的元素
在C++中,可以使用std::map容器来存储键值对,并且可以通过指针来替换元素。下面是一个示例代码:
#include <iostream>
#include <map>
int main() {
std::map<int, int> myMap;
myMap[1] = 10;
myMap[2] = 20;
// 获取指向元素的指针
std::map<int, int>::iterator it = myMap.find(1);
if (it != myMap.end()) {
// 替换元素的值
it->second = 100;
}
// 输出替换后的值
for (it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
return 0;
}
在上面的代码中,首先创建了一个std::map容器myMap,并向其中插入了两个键值对。然后,通过find函数查找键为1的元素,并将返回的迭代器保存到it中。接下来,通过it->second访问元素的值,并将其替换为100。最后,使用迭代器遍历myMap并输出替换后的键值对。
原文地址: https://www.cveoy.top/t/topic/pURr 著作权归作者所有。请勿转载和采集!