en4bz
en4bz

Reputation: 1132

Comparing .end() against a value

I'm writing a board game with an bizarre layout so I have a map from a point to the places's value. If the place is empty it isn't in the map therefore if find returns end() the place is empty. If I want to check what a particular place's colour is i use the following. Is this code valid? Or in other word is it safe to compare end against lColour

enum COLOUR {BLACK,WHITE}

this->mBoard.find(Point(p.x - 1, p.y))->second == lColour

where lColour is of type COLOUR

Upvotes: 0

Views: 73

Answers (3)

Thomas Sidoti
Thomas Sidoti

Reputation: 193

No.

You should check that the iterator returned by find != end before trying to get the second element.

const auto& point_color = this->mBoard.find(Point(p.x - 1, p.y);
if (point_color != this->mBoard.end() &&
    point_color->second == lColour) {
  // something
}

Upvotes: 2

john
john

Reputation: 87997

No it's not because it would mean dereferencing the end iterator and that is undefined behaviour.

Upvotes: 1

No, what you're doing is not safe. The past-the-end iterator (the one returned by end()) cannot be dereferenced. You're doing -> on the result of find(): if that result is past-the-end, you're invoking undefined behaviour.

Upvotes: 2

Related Questions