Home > Net >  problem with operator[] when trying to access a vector of shared_ptr
problem with operator[] when trying to access a vector of shared_ptr

Time:09-17

I have the following class :

class Character
{
     /unimportant code
}
class Fighter : public Character
{
     /unimportant code
}
class Healer: public Character
{
     /unimportant code
}


class Game
{
public:
    void move(const GridPoint & src_coordinates,  const GridPoint & dst_coordinates);
    //there are more things here ,but they're not important for the sake of this question. 
private:
    int height;
    int width;
    std::vector<std::shared_ptr<Character>> gameboard;
};


void move(const GridPoint & src_coordinates,  const GridPoint & dst_coordinates)
{
    for (std::vector<std::shared_ptr<Character>>::iterator i = gameboard.begin(); i != 
                                                                  gameboard.end() ; i   )
    {
        if ( (*gameboard[i]).coordinates == src_coordinates)
        {
            //do I need to implement my own [] operator?
        }
           
        
    }
        
}

Im trying to iterate over my gameboard and move the character from src_coordinates to dst_coordinates. Character is also a class that's inherited by a few more :

I get the following error when I try to access the elements of gameboard[i] :

no match for 'operator[] (operand types are 'std::vector<std::shared_ptr<Character> >' and 'std::vector<std::shared_ptr<Character> >::iterator' {aka '__gnu_cxx::__normal_iterator<std::shared_ptr<Character>*, std::vector<std::shared_ptr<Character> > >'}

does that mean that I have to implement my own operator[] and operator* because Character is a class of my own? and how can I solve my ptoblem?

CodePudding user response:

Iterators are a generalization of pointers. You use * to get the pointed-at thing from a pointer; you use * to get the element of a container that an iterator is currently "pointing at". The iterator type uses operator overloading so that it can behave like a pointer, even when the underlying container isn't a simple array.

std::vector<std::shared_ptr<Character>>::iterator

This means: "a thing that, when you apply * to it, gives you a std::shared_ptr<Character> that came from a std::vector<std::shared_ptr<Character>> (among other useful properties)".

Each time through the loop, *i is one of the std::shared_ptr<Character>s in the vector. Therefore, (*i)->coordinates are the coordinates of the Character that the shared_ptr points at. (Notice ->, because we also have to dereference the shared_ptr.)

no match for 'operator[]

This happens because you are trying to use the iterator as if it were an index. You can clearly see what is wrong with the following code:

char[] example = "hello, world\n";
char* ptr = &example[0];
example[ptr]; // wait, what?
  • Related