1

I try to change an object using an iterator, but I get this Error:

Error 1 error C2662: 'void Item::setCount(int)' : cannot convert 'this' pointer from 'const Item' to 'Item &'

1 IntelliSense: the object has type qualifiers that are not compatible with the member function

This is my code:

void Customer::addItem(Item other)//add item to the set
{
    set<Item>::iterator it;
    it = _items.find(other);

    if (it != _items.end())
    {
        it->setCount( (this->getCount((*it)) + 1) );
    }

    else
        _items.insert(other);
}

And in this line I have error:

it->setCount( (this->getCount((*it)) + 1) );
Rakete1111
  • 47,013
  • 16
  • 123
  • 162
Yair B.
  • 322
  • 1
  • 2
  • 12

1 Answers1

4

The iterator for an std::set is const, since modifying the entry can impact the ordering.

To get around this, either :

  • choose a different container
  • do a delete+add operation (ie. remove the item from the set, modify it, and then add it into the set again)
  • use mutable on the fields modified by setCount (if appropriate)
  • use const_cast to cast away the constness of the item before calling setCount (as a last resort)

For the latter two options, make sure that setCount does not modify anything that changes the ordering of Item objects though.

Sander De Dycker
  • 16,053
  • 1
  • 35
  • 40
  • Thanks you for comment. What can i do if I want to update the counter of my item if I can't using set ? – Yair B. Jan 18 '17 at 11:04
  • @Yair - difficult to say without seeing your `Item` class, but your best bet is probably " choose a different container". In your case I would recommend removing the count from the item (after all, an item might have a name, a colour, a weight - but it typically doesn't have a count), and using `std::map` (or `unordered_map`) to store the counts. – Allison Lock Jan 18 '17 at 11:09
  • 1
    @YairB. : I've added some more details to my answer, which will hopefully clarify things a bit better. – Sander De Dycker Jan 18 '17 at 13:06