C++ 如何使用指针处理地图?

C++ 如何使用指针处理地图?,c++,pointers,map,C++,Pointers,Map,考虑到我有一个叫人的班级。我在地图上存储指向这些人的指针 map<string, People*> myMap; 但是这给了我一个分段错误,它甚至没有调用People类的构造函数 我也试过了 myMap.insert( std::make_pair( "dave", new People() )); 但这并没有改变任何事情,构造器仍然没有被调用,并且程序关闭了处理这段代码的过程,出现了一个分段错误 如何访问和操作带有指针的地图?为什么上面的方法不起作用,我没有得到编译时错误或警

考虑到我有一个叫人的班级。我在地图上存储指向这些人的指针

map<string, People*> myMap;
但是这给了我一个分段错误,它甚至没有调用People类的构造函数

我也试过了

 myMap.insert( std::make_pair( "dave", new People() ));
但这并没有改变任何事情,构造器仍然没有被调用,并且程序关闭了处理这段代码的过程,出现了一个分段错误

如何访问和操作带有指针的地图?为什么上面的方法不起作用,我没有得到编译时错误或警告

非常感谢您的任何见解,感谢您提供地图:

map<string, People*> myMap;
然后,内存管理全部为您处理,使用
操作符[]
将根据需要构建新的人员。

试试看

myMap["dave"] = new People(....);
new
将调用构造函数,返回指针并将其插入到映射中


不过,您需要小心内存泄漏。使用智能指针解决此问题。

如果您想堆分配
人员
,但要使用映射,请看一看,特别是
boost::ptr\u映射
。它只是标题,所以您不需要编译任何额外的库

#include <iostream>
#include <string>
#include <boost/ptr_container/ptr_map.hpp>

struct People
{
    int age;
};

typedef boost::ptr_map<std::string,People> PeopleMap;

int main(int,char**)
{
    PeopleMap data;

    data["Alice"].age = 20;
    data["Bob"].age = 30;

    for (PeopleMap::const_iterator it = data.begin(); it != data.end(); ++it)
        std::cout << "Name: " << it->first << " Age: " << it->second->age << std::endl;

    return 0;
}
#包括
#包括
#包括
结构人
{
智力年龄;
};
typedef boost::ptr_地图人物地图;
int main(int,char**)
{
人口地图数据;
数据[“Alice”]。年龄=20岁;
数据[“鲍勃”]。年龄=30岁;
对于(PeopleMap::const_迭代器it=data.begin();it!=data.end();++it)
std::cout尝试使用:

People* new_people = new People (member_variable1,member_variable2);

myMap.insert(std::pair<std::string, People*>("key for string",new_people) );
People*new\u People=新人(member\u variable1,member\u variable2);
insert(std::pair(“字符串的键”,new_people));
否则:

People new_people(member_variable1,member_variable2);
myMap.insert(std::pair<std::string, People*>("key for string",&new_people) );
新成员(成员变量1、成员变量2);
insert(std::pair(“字符串的键”和new_people));
两者都会起作用

People* new_people = new People (member_variable1,member_variable2);

myMap.insert(std::pair<std::string, People*>("key for string",new_people) );
People new_people(member_variable1,member_variable2);
myMap.insert(std::pair<std::string, People*>("key for string",&new_people) );