How to process a map using pointers?

I have People class names. I keep pointers to these people on the map.

map<string, People*> myMap;

To create new people, I use the maps [] operator.

myMap["dave"]->sayHello();

But that gives me segmentation errors and doesn't even call the constructor of the People class.

I also tried

 myMap.insert( std::make_pair( "dave", new People() ));

But this has not changed anything, the constructor is still not being called, and the program disables the processing of this code with a segmentation error.

How do I access and manipulate a map using pointers in them? Why does not work above, I do not see compilation errors or warnings.

Any insight is much appreciated, thanks

+5
source share
4 answers

Given the map:

map<string, People*> myMap;

operator[] People, People*, , -.

, , , :

map<string, People> myMap;

, operator[] .

+9

Try

myMap["dave"] = new People(....);

new , .

. , .

+2

People, , Boost Pointer Containers, boost::ptr_map, , .

#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;
}
0

:

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) );

!!!

0

All Articles