简体   繁体   中英

I'm trying to insert to a set of a class

I have 2 classes: Item and Customer, and I want to insert an item into the set of item (the set of items is in the customer). The problem is that I want to change the count in the item and I have trouble with it because the iterator won't work with non-const functions such as setCount... so this doesn't compile:

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

but if i put const in the setCount it won't compile either because i cant change the value of count.

Does anyone have an idea what to do?

Thanks in advance

You simply cannot call non- const methods on objects that you put in a set , as per §23.2.4/5-6 (in N3797, emphasis mine):

(5) For set and multiset the value type is the same as the key type.

(6) iterator of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators.

So when you try to do:

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

That can't work, since the object it points to is const . If you still want to store the count internally to the object AND in a set, you can make whatever the count member variable is mutable and still mark setCount() to be const .

Far more likely though, the container you want is something like std::map<std::string, Item> , where your logic would be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM