I'm trying to iterate through a Players hand of cards.
#include <vector> #include <iostream> class Card { int card_colour, card_type; public: std::string display_card(); }; std::string Card::display_card(){ std::stringstream s_card_details; s_card_details << "Colour: " << card_colour << "\n"; s_card_details << "Type: " << card_type << "\n"; return s_card_details.str(); } int main() { std::vector<Card*>current_cards; vector<Card*>::iterator iter; for(iter = current_cards.begin(); iter != current_cards.end(); iter++) { std::cout << iter->display_card() << std::endl; } }
This line
std::cout << iter->display_card() << std::endl;
currently comes up with the
error: Expression must have pointer-to-class type.
How can I fix this?
Use a for loop and reference pointer In C++ , vectors can be indexed with []operator , similar to arrays. To iterate through the vector, run a for loop from i = 0 to i = vec. size() .
You can store pointers in a vector just like you would anything else. Declare a vector of pointers like this: vector<MyClass*> vec; The important thing to remember is that a vector stores values without regard for what those values represent.
An ordinary vector encountered in C++ programming, is a vector of objects of the same type. These objects can be fundamental objects or objects instantiated from a class. This article illustrates examples of vector of pointers, to same object type.
Try this:
cout << (*iter)->display_card() << endl;
The *
operator gives you the item referenced by the iterator, which in your case is a pointer. Then you use the ->
to dereference that pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With