C++ 使用指针添加元素到 Map 中
在 C++ 中,可以使用指针来添加元素到 map 中。以下是一个示例代码:
#include <iostream>
#include <map>
int main() {
std::map<int, int> myMap;
std::map<int, int>* mapPtr = &myMap;
// 添加元素到 map 中
mapPtr->insert(std::pair<int, int>(1, 10));
mapPtr->insert(std::pair<int, int>(2, 20));
mapPtr->insert(std::pair<int, int>(3, 30));
// 遍历 map 并输出元素
for (const auto& pair : *mapPtr) {
std::cout << pair.first << " : " << pair.second << std::endl;
}
return 0;
}
在上面的示例中,首先创建了一个 std::map<int, int> 类型的对象 myMap。然后,创建了一个指向这个 map 对象的指针 mapPtr,并将其赋值为 &myMap。接下来,使用指针 mapPtr 来添加元素到 map 中,可以使用 insert 函数来插入键值对。最后,通过遍历 map 来输出所有的键值对。
请注意,使用指针操作 map 时,需要使用 -> 来访问 map 的成员函数和成员变量。
原文地址: https://www.cveoy.top/t/topic/pURw 著作权归作者所有。请勿转载和采集!