CreasyBear
CreasyBear

Reputation: 65

C++ Map with value that is a pointer

If I have a map of typestd::map<std::string, Person> where Person is a class I have defined, the following is how I would access the Person at the iterator it:

it->second;

But what if the map was of typestd::map<std::string, Person*>, in which case the element would be a pointer to a Person, rather than an actual Person. How would I then access the Person? For example, is this correct:

*it->second;

or is this:

it->*second;

Thanks!

Upvotes: 0

Views: 2101

Answers (2)

ThomasMcLeod
ThomasMcLeod

Reputation: 7769

Person const & person = *it->second;
std::cout << person.name << std::endl;
std::cout << person.address << std::endl;
//etc

Or simply

std::cout << it->second->name << std::endl;
std::cout << it->second->address << std::endl;

Upvotes: 0

djechlin
djechlin

Reputation: 60758

Well you'd most likely access it->second->name, for instance. but *(it->second) is correct (I think you don't need the ( ), can't remember; check operator precedence.)

Upvotes: 2

Related Questions