简体   繁体   中英

Accessing Member Functions of Objects in a Map in C++

From what i understand, and correct me if i am wrong on any of the following, containers are used to store objects.. a map is an associative container, it stores objects as "elements".

If so, how can i access the member functions of those objects (eg setters and the getters) like how i do when i create an object without a map to set parameters?

or to put in another way, how can i do the equivalent of:

someClass someObject;
someObject.setSomething(InputVari);

of a map?

You need to use the [] operator .

myMap[myIndex].setVariable(aValue);

For example, if you wanted to create a map of class Person with a character for the key, where people had a first name, last name, and current location, along with a setCurrentLocation(std::string aNewLocation) parameter it would look something like the following.

std::map<char, Person> myMap;

Person myPerlmaoooosonOne("Phill", "Collins", "England");

myMap['A'] = myPersonOne;

myMap['A'].setNewLocation("New York")

correct me if i am wrong on any of the following, containers are used to store objects

Not necessarily. There are cases when storing the pointer to object is preferable, like when objects are big, and thus taking copies of the object is expensive. Another case is when the object is polymorphic, and you want to store objects of different derived classes in the container. Storing pointer prevents from object slicing .

To access the members of the object:

class Foo{ int A; void bar(){} }; 

map<string, Foo*> myMap;

auto it = myMap.find("keyToObject");

if(it != myMap.end()) {
  it->A += 1; it->bar();  
}

You need to be little careful while using [] with std::map , considering the fact, [] is little more than a convenient notation for insert() . The result of myMap[k] is equivalent to the result of (∗(myMap.insert(make_pair(k,V{})).first)).second , where V is the mapped type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM