c++ - 插入指向 std::map 的指针

标签 c++ dictionary stl stdmap

我在 map 中使用 map:

std::map<int, std::map<DWORD,IDLL::CClass*>*> *MyMap

我使用以下代码插入 map :

std::map<DWORD,IDLL::CClass*> *SecondMap;
SecondMap= new std::map<DWORD,IDLL::CClass*>; 
DWORD i = 1;
while (eteration on obj type IDLL::CClass ) 
{
     SecondMap.insert(std::make_pair(i,&obj));           
}int j = 1;    


MyMap->insert(std::make_pair(1,&SecondMap));

稍后在程序中, map 已变为空!

请问有人可以帮忙吗?

最佳答案

拥有拥有原始指针一般来说是一种不好的做法(除非您在特殊情况下,例如您正在构建自定义高级数据结构,并且拥有的原始指针在适当的 RAII 类边界中受到保护)。

第一个选项应该是使用值语义;如果这对您的性能不利,那么您可能需要使用智能指针,例如shared_ptr(这有助于使您的代码更简单,使其异常安全,避免资源泄漏等)。

这是一个示例可编译代码,似乎可以在 VS2010 SP1 (VC10) 上运行:

#include <iostream>     // for std::cout
#include <map>          // for std::map
#include <memory>       // for std::shared_ptr and std::make_shared
using namespace std;

typedef unsigned int DWORD;    

struct MyClass
{
    MyClass() : Data(0) {}
    explicit MyClass(int data) : Data(data) {}

    int Data;
};

int main()
{
    //
    // Build some test maps
    //

    typedef map<DWORD, shared_ptr<MyClass>> InnerMap;
    typedef map<int, shared_ptr<InnerMap>> OuterMap;

    auto innerMap1 = make_shared<InnerMap>();
    (*innerMap1)[10] = make_shared<MyClass>(10);
    (*innerMap1)[20] = make_shared<MyClass>(20);

    OuterMap myMap;

    myMap[30] = innerMap1;


    //
    // Testing code for maps access
    //

    const int keyOuter = 30;
    auto itOuter = myMap.find(keyOuter);
    if (itOuter != myMap.end())
    {
        // Key present in outer map.
        // Repeat find in inner map.

        auto innerMapPtr = itOuter->second;
        const DWORD keyInner = 20;
        auto itInner = innerMapPtr->find(keyInner);
        if (itInner !=  innerMapPtr->end())
        {
            cout << itInner->second->Data << '\n';
        }
    }
}

关于c++ - 插入指向 std::map 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15367831/

相关文章:

c++ - 是否可以使用超出范围的 RA 迭代器?

c++ - 如何同步 CGI 编程?

C++ 约定——类的源文件和头文件

c++ - 为什么我不能为 std::vector 元素取别名?

python - 抓取链接和标题 - 使用 beautifulsoup 存储在字典中

c++ - 从 std::set::insert() 返回迭代器是常量?

c++ - 真的, "fixed"I/O 操纵器的反面是什么?

python - Pandas dataframe to dict,同时保留重复行

c++ - std::map:只使用keytype的一部分进行比较查找

c++ - VC++ 允许对 STL 容器使用 const 类型。为什么?