c++ - How to return the value of a pointer in a list? -


i've got "faction" class, , vector of pointers want turn list. method it. assume i've managed turn vector of pointers list alright in first part, want print list out within method. know using '*', i'm printing out memory location opposed value, , that's code doing.

list<faction*> faction::linklistfactions() {     list<faction*> list_factions(factionptr_.begin(), factionptr_.end());     cout << "printing linked list:" << endl;     (int = 0; < list_factions.size(); a++)    {       std::list<faction*>::iterator = list_factions.begin();       advance(i, a);       cout << *i;       cout << ",";    }     return list_factions; } 

but want print out value, not memory location. instead of

cout << *i; 

i can like

cout << i->getfactionname(); 

i able vector, simple enough:

string faction::getfactionname() const {      return factionname_; } 

but i'm having trouble coming similar method list. doesn't work same, , i'm not sure why. perhaps there's way?

first of all, iteration o(n^2) instead of o(n) (because advance() on list::iterator have call ++ a times - it's linear-time operation). proper way in c++03 iterate through list use iterators:

for (std::list<faction*>::iterator = list_factions.begin();       != list_factions.end(); ++i) {     ... } 

which in c++11 reduces to:

for (faction* : list_factions) { ... } 

secondly, i "points" faction*: *i faction*, means if want call faction member functions, have additionally dereference it:

std::cout << (*i)->getfactionname() << std::endl; 

lastly, unless you're really sure need list, stick vector.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -