brianpmaher
brianpmaher

Reputation: 101

Error: Vector iterator not dereferencing

I just inserted into a vector and all is well, when I went to insert next, with the vector iterator currently pointing at vectorname.begin(). Since I only have one value, the guard I have should stop it from iterating, but it breaks for some reason. I feel like I'm not accessing the end correct, or stopping the iteration.. either way, here's the code that's breaking.

// check if iterator X and Y are equal to destX and destY
if(iter != this->playerVector.end())
{
    while((iter->myX != destX) && (iter->myY != destY) || (iter != this->playerVector.end()))
    {
        iter++;
    }
}

it breaks when checking the while statements after one iteration.

Upvotes: 0

Views: 563

Answers (2)

Kashyap
Kashyap

Reputation: 17556

If what you want to do is "// check if iterator X and Y are equal to destX and destY" then you've made it more complex than needed..

while(iter != this->playerVector.end())
{
  if(iter->myX == destX && iter->myY == destY) {
    cout << "found destX/Y at " << iter << endl;
    break;
  }
  iter++;
}

-- edit --

also know that when you write such looong statements like x || y ^ z && a & b..., then you also have to take operator precedence in account, though in this case I guess only problem they cause is to make it unreadable.

Upvotes: 0

iammilind
iammilind

Reputation: 70094

It seems you are missing proper conditioning in the while loop and that's why it's always true (also put braces when you have various operators in place). Your condition should be,

while((iter->myX != destX) && (iter->myY != destY) && (iter != this->playerVector.end()))

Following is another simple version of your while loop:

while(iter != this->playerVector.end())
{
  if(iter->myX == destX || iter->myY == destY)
    break;
  iter++;
}

Upvotes: 2

Related Questions