gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:51:38 24 4
gpt4 key购买 nike

我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com