在C++中,可以使用std::map来创建一个键值对映射的容器。要向std::map中添加元素,可以通过指针的方式来操作。

以下是使用指针向std::map添加元素的示例代码:

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string>* myMapPtr = new std::map<int, std::string>;

    // 添加元素
    myMapPtr->insert({1, "One"});
    myMapPtr->insert({2, "Two"});
    myMapPtr->insert({3, "Three"});

    // 遍历元素
    for (auto it = myMapPtr->begin(); it != myMapPtr->end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }

    // 删除元素
    myMapPtr->erase(2);

    // 遍历元素
    for (auto it = myMapPtr->begin(); it != myMapPtr->end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }

    // 释放内存
    delete myMapPtr;

    return 0;
}

在这个示例中,我们首先创建了一个std::map指针myMapPtr,然后使用insert函数向std::map中添加了三个键值对。接着,我们使用for循环遍历std::map中的元素,并打印出键和值。然后,我们使用erase函数删除了键为2的元素,并再次遍历std::map中的元素进行验证。最后,我们通过delete释放了myMapPtr指针所指向的内存空间。

注意,使用指针来操作std::map时,需要注意内存管理和避免空指针异常等问题

c++ map指针 添加元素

原文地址: http://www.cveoy.top/t/topic/ib9s 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录