【问题标题】:I'm trying to insert to a set of a class我正在尝试插入一组类
【发布时间】:2015-01-09 20:38:46
【问题描述】:

我有 2 个类:Item 和 Customer,我想将一个项目插入到项目集中(项目集在客户中)。 问题是我想更改项目中的计数,但我遇到了麻烦,因为迭代器无法与 setCount 等非 const 函数一起使用......所以这不会编译:

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 的值。

有人知道该怎么做吗?

提前致谢

【问题讨论】:

  • 首先,您为什么将参数设为Item *,然后通过按值复制将其插入集合中?如果这是您的意图,则将参数作为 const Item &amp; 代替。如果这不是您的意图,那么您可能会泄漏内存。其次,不清楚你看到了什么问题,因为这段代码实际上并没有重现这个问题。
  • 请不要实施任何变通办法:'if' 和 'for' 是一些。
  • @mbgda 但我还需要更改计数,所以这不是我的问题...
  • @DieterLücking 我不明白你的意思......
  • 非常不清楚您在这里实际想要完成什么。为什么该项目需要知道它在集合中存在多少个副本?每次添加或删除副本时,您都需要更新每个具有相同名称的剩余项目的计数。如果 Item 内部的数据对于所有实例都是相同的,为什么不只更新集合中现有 Item 的计数,而不是每次插入一个新实例并更新所有实例?

标签: c++ stl compilation set constants


【解决方案1】:

根据 §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&lt;std::string, Item&gt;,您的逻辑是:

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

【讨论】:

    猜你喜欢
    • 2015-05-26
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    相关资源
    最近更新 更多