2015-01-09 80 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); 
}