Iterating through a vector of pointers

后端 未结 3 1172
青春惊慌失措
青春惊慌失措 2020-12-28 17:03

I\'m trying to iterate through a Players hand of cards.

Player.cpp

vector::iterator iter;
    for(iter = current_car         


        
相关标签:
3条回答
  • 2020-12-28 17:50

    You have to 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 the iter++ which you should avoid in profit of ++iter (see https://stackoverflow.com/a/24904/2077394). Depending on the container, you may also want to avoid calling end() each iteration.

    (By the way it always help to provide a minimal reproducible example like I just wrote when you ask question.)

    0 讨论(0)
  • 2020-12-28 17:53

    De-referencing the iterator by iter-> gives a pointer to an object of type Card, you have to write (*iter)->display_card();

    0 讨论(0)
  • 2020-12-28 18:06

    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.

    0 讨论(0)
提交回复
热议问题