通过迭代器更改对象

时间:2017-01-18 10:52:49

标签: c++ iterator

我尝试使用迭代器更改对象,但是我收到此错误:

  

错误1错误C2662:' void Item :: setCount(int)' :无法转换   '这'指针来自' const Item'到'项目&'

     

1智能感知:对象的类型限定符不是   与成员函数兼容

这是我的代码:

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);
}

在这一行我有错误:

it->setCount( (this->getCount((*it)) + 1) );

1 个答案:

答案 0 :(得分:3)

std::set的迭代器是const,因为修改条目会影响排序。

要解决这个问题,请:

  • 选择其他容器
  • 执行删除+添加操作(即从集合中删除项目,修改它,然后再将其添加到集合中)
  • setCount修改的字段(如果适用)
  • 上使用mutable
  • 在致电const之前使用const_cast丢弃该项目的setCount(作为最后手段)

对于后两个选项,请确保setCount不会修改任何会改变Item个对象排序的内容。