skm
skm

Reputation: 5679

mapping from String to a Class type using map<> from STL

I have a class Person which could be of type (an attribute of this class) EMPLOYEE, STUDENT, ALUMNI. In a text file, the names (e.g. "John", "Lena", "Mac" etc.) of some Persons are given. The names of persons are in string type.

The text file looks as following:

STUDENT(John)
STUDENT(Victor)
EMPLOYEE(Mary)
ALUMNI(Mac)

Problem: I want to map the names which are in string type into Person type. I need something similar to

std::map<string, Person*> person_list;

but it is not possible to do so directly.

I am struck at:

while()
{
    ----
    ----
    string person_name = line.substr( index + 1, ( line.find_first_of(')', index) - index - 1) );
    person_list[person_name] = ?????
}

I cannot use person_list[person_name] = new Person() because i have to do that in another method given below

Person* University::addInput(string name) //Input name was sent as a string from the calling function
{
    Person* new_input = new Person(INPUT, name);
    inputs.push_back(new_input);
    return new_input;
}

Summary: Whenever i find a person name in my file, i just want to make a new object of type Person with an unique id so that i can find it later on.

PS: Just a side remark. I want to map from string to Personbecause i have an another method which establish a connection between two persons i.e. connect(Person* a, Person* b); but only when certain conditions get fulfilled. So, after mapping all the persons, i need to track them again to connect them based upon some conditions.

Upvotes: 0

Views: 169

Answers (1)

eerorika
eerorika

Reputation: 238471

You need to create an instance of the class Person. Are you sure that you must store pointers instead of objects in the map? Memory management will be much easier if you let the map own the objects like this:

std::map<std::string, Person> person_list;
// while...
Person person; // instantiate an object
person.name = person_name; // you probably want to set some data...
person_list[person_name] = person;

Update according to edit...

Ok, the person object in constructed in the addInput function and it returns a pointer to the person. If you absolutely must use that, you can do this:

std::map<std::string, Person*> person_list;
// while...
Person* person = University::addInput(INPUT(), person_name);
person_list[person_name] = person;

Just remember to delete the Person objects that were created with new before inputs is destroyed... or consider storing the objects in that container instead of their pointers. And make sure that person_list does not live longer than inputs... or use shared_ptr

Upvotes: 4

Related Questions