Search code examples
c++listcompiler-errorsiteratorconstants

C++ List Iterator cant be initlaized


I have two functions in my Character class:

void Character::dropItem(const Item & item)
{
    for (list<const Item*>::iterator i = playerInventory.inventory.begin(); i != playerInventory.inventory.end(); i++) {
        if ((*i) == &item) {
            playerInventory.inventory.erase(i);
            break;
        }
    }
}

double Character::getTotalWeight() const
{
    for (list<const Item*>::iterator i = playerInventory.inventory.begin(); i != playerInventory.inventory.end(); i++) {

    }
}

However, Visual Studio gives me an error

Error   C2440   'initializing': cannot convert from 'std::_List_const_iterator<std::_List_val<std::_List_simple_types<_Ty>>>' to 'std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>'

on playerInventory in the first statement of the for loop in getTotalWeight(). I can't figure out why this error is occurring, because it's literally the same loop as the function just above it. Any insight is appreciated.


Solution

  • The function is a constant member function

    double Character::getTotalWeight() const
    

    So the data member playerInventory.inventory is considered as a constant data member. As a result you may not use a non-constant iterator.

    Write instead

    for (list<const Item*>::const_iterator i = playerInventory.inventory.cbegin(); i != playerInventory.inventory.cend(); i++) {
    

    That is the member function begin returna const_iterator while you are trying to assign it to iterator and there is no corresponding conversion from the first iterator type to the second iterator type.