Iterate over a pointer vector

I am trying to iterate using a player map.

Player.cpp

vector<Card*>::iterator iter; for(iter = current_cards.begin(); iter != current_cards.end(); iter++) { cout << iter->display_card() << endl; } 

Itera in

 cout << iter->display_card() << endl; 

an error is currently appearing: the expression must be of type of a pointer to a class.

Similarly, current_cards is declared using:

 vector<Card*>current_cards; 

In addition, the display_card () method is simple:

Card.cpp

 string Card::display_card(){ stringstream s_card_details; s_card_details << "Colour: " << card_colour << "\n"; s_card_details << "Type: " << card_type << "\n"; return s_card_details.str(); } 

I looked at various resources, and everything that was suggested for these types of problems did not work for me. Thanks for any help!

+7
c ++ object pointers vector
source share
3 answers

Try the following:

 cout << (*iter)->display_card() << endl; 

The * operator provides you with the element that the iterator refers to, which in your case is a pointer. Then you use -> to dereference this pointer.

+22
source share

You must dereference the iterator to access the pointer:

 #include <vector> #include <iostream> class Card { public: std::string display_card(); }; int main() { std::vector<Card*>current_cards; std::vector<Card*>::iterator iter, end; for(iter = current_cards.begin(), end = current_cards.end() ; iter != end; ++iter) { std::cout << (*iter)->display_card() << std::endl; } } 

Another observation is iter++ , which should be avoided when using the ++iter (see https://stackoverflow.com/a/16718/ ). Depending on the container, you can also avoid calling end () of each iteration.

(By the way, this always helps to provide a minimal reproducible example, as I just wrote when you ask a question.)

+2
source share

Removing a link to the iter iter-> gives a pointer to an object of type Card, you need to write (* iter) → display_card ();

+1
source share

All Articles