Question

void Player::removeWeapon(int location)
{
    if (location<(int)weaponInCharacter.size()) {
        weaponInCharacter.erase(weaponInCharacter.begin() + location);
    }
}

I'm unsure of the following line:

if (location<(int)weaponInCharacter.size()) {

I can see that its comparing the int location to the location in the vector weaponInCharacter but what is it doing between the int and the vector in this part of the code :(int)weaponInCharacter.size())

Était-ce utile?

La solution

The (int) is simply the old C-style cast of the value to int.

This is a very common idiom. The return value of size is size_t, which is unsigned. When you try to compare this to a signed int, many compilers will give a warning. To eliminate the warning you can simply cast the size_t to an int and everything will be OK, as long as you know that the value returned by size will fit in an int. It would be vanishingly rare for the return value not to fit in an int.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top