-2
std::vector<Piece*> player1, player2;

/* Filling player 1 and 2 vith piece 
   player1.push_back(new Piece()) */

std::vector<Piece*> *currentPlayer, *opponent;

currentPlayer = &player1;
opponent      = &player2

for(int i = 0; i < currentPlayer.size(); ++i)
{
    // This is where i get the error
    // error: base operand of '->' has non-pointer type 'std::vector<Piece*>'
    currentPlayer[i]->memberFunctionOfPiece()
}

As you can see I am trying to use a pointer pointing to a vector of pointers. but getting non-pointer type when trying to access the vector Why can't i access the member function?

sskirren
  • 13
  • 3
  • I am certain there's a duplicate for it, but I can't for the life of me, to find an exact duplicate. But, related: https://stackoverflow.com/questions/6946217/pointer-to-a-vector . – Algirdas Preidžius Dec 06 '17 at 23:32
  • 1
    `currentPlayer[i]` "works" because of pointer arithmetic. You need `(*currentPlayer)[i]`. And the condition in the for loop would fail; you need `for(int i = 0; i < currentPlayer->size(); ++i)` – Justin Dec 06 '17 at 23:34
  • 1
    Life would be much easier if you stop using pointers – M.M Dec 06 '17 at 23:35
  • 1
    this code has to be wrong: `currentPlayer.size()` is invalid. Part of your code wants currentplayer to be a vector, other parts want to be a pointer to a vector. Which is it? – pm100 Dec 06 '17 at 23:42

2 Answers2

2

The problem is that you are trying to use square brackets on a pointer type:

currentPlayer[i]->memberFunctionOfPiece();

you can use operator[] or even better use the at function

currentPlayer->at(i)->memberFunctionOfPiece();

or

currentPlayer->operator[](i)->memberFunctionOfPiece();
Adam Snaider
  • 188
  • 1
  • 8
0

You could also use ranged for loop on STL containers

for(auto&& player : *currentPlayer)
{
    player->memberFunctionOfPiece();
}
Max Rahm
  • 684
  • 11
  • 25