我正在尝试插入一组类

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

本文关键字:一组 插入      更新时间:2023-10-16

我有 2 个类:项目和客户,我想将一个项目插入到项目集中(项目集在客户中)。问题是我想更改项目中的计数,但我遇到了麻烦,因为迭代器无法使用 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);
        }
    }
}

但是如果我将 const 放在 setCount 中,它也不会编译,因为我无法更改 count 的值。

有人知道该怎么做吗?

提前致谢

根据 §23.2.4/5-6(在 N3797 中,强调我的),您根本无法对放入set的对象调用非const方法:

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