Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

c++ - Iterating through a vector of pointers

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 << "
";
  s_card_details << "Type: " << card_type << "
";
    
  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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...