Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through a vector of pointers

Tags:

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?

like image 864
Red Shift Avatar asked Apr 27 '14 02:04

Red Shift


People also ask

How do you iterate through a vector of pointers?

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() .

Can you have a vector of pointers?

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.

What is a vector of pointers in C++?

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.


1 Answers

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.

like image 72
Reto Koradi Avatar answered Sep 20 '22 18:09

Reto Koradi