2015-01-09 26 views
0

我有2个类:项目和客户,我想插入项目的集合(项目集在客户中)。 问题是我想改变项目中的计数,我有麻烦,因为迭代器将不会使用非const函数,如setCount ...所以这不会编译:我试图插入一组类

void Customer::insertItem(Item *newItem) 
{ 
    std::set<Item>::iterator it; 
    if (newItem->getCount() == 0) 
    { 
     _items.insert(*newItem); 
    } 
    for (it = _items.begin(); it != _items.end(); it++) 
    { 
     if (_items.find(*newItem) != _items.end()&&it->getName()==newItem->getName()) 
     { 
      it->setCount(it->getCount() + 1); 
     } 
    } 
} 

但如果我把常量放在setCount中,它也不会编译,因为我不能改变count的值。

有没有人有想法该怎么办?

在此先感谢

+0

首先,你为什么要采取一个参数为'项目*',然后将其插入到通过按值复制设置?如果这是你的意图,那么把该参数作为一个'const Item&'来代替。如果这不是你的意图,那么你可能会泄漏记忆。 其次,目前还不清楚你看到了什么问题,因为这段代码实际上并没有重现这个问题。 – mbgda 2015-01-09 20:42:32

+0

请不要实施任何解决方法:'if'和'for'是一些。 – 2015-01-09 20:42:48

+0

@mbgda但我也需要改变计数,所以这不是我的问题... – 2015-01-09 20:47:31

回答

2

你根本无法调用非const方法上,你把一个set对象,按§23.2.4/ 5-6(在N3797,重点煤矿):

(5)对于setmultiset,值类型与密钥类型相同。

(6)关联容器的iterator属于双向迭代器类别。对于值类型与密钥类型相同的关联容器,iteratorconst_iterator都是常数迭代器。

所以,当你尝试做:

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

这不能工作,因为对象it点是const。如果您仍然想要将计数内部存储到对象AND中,您可以使计数成员变量为mutable且仍将setCount()标记为const

远更可能的是,你想要的容器是像std::map<std::string, Item>,你的逻辑是:

void Customer::insertItem(const Item& newItem) 
{ 
    auto it = _items.find(newItem.getName()); 
    if (it == _items.end()) { 
     // absent, insert it 
     it = _items.insert(std::make_pair(newItem.getName(), newItem)).first; 
    } 

    // now increment the count 
    // it->first is a const Key, but it->second is just Value, so it's mutable 
    it->second.setCount(it->second.getCount() + 1); 
}