我正在尝试插入一组类
I'm trying to insert to a set of a class
我有 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) 对于
set
和multiset
,值类型与键类型相同。(6) 关联容器
iterator
属于双向迭代器类别。对于值类型与键类型相同的关联容器,iterator
和const_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);
}
相关文章:
- 在 c++ 中拥有一组结构的正确方法是什么?
- nlohmann-json将一个数组插入到另一个数组中
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 一组值的零开销下标运算符
- 使用一组结构,避免在一组结构中出现重复的结构
- CMake:我们可以为一组不形成可执行文件或库的特定文件指定包含目录吗?
- 合并一组模板专用化
- 如何更好地检查两个 char 变量是否在一组值中?
- C++有没有办法强制重写一组方法,如果其中一个方法在子类中具有重写?
- 给定一个枢轴点,按照它们与枢轴点构成的角度递增顺序对一组点进行排序
- 如何从一组变量中查找最低值
- 类数组插入函数
- 如何根据对的第二个元素对 STL c++ 中的一组对进行排序?
- 如何插入一组已传递给已经声明的函数的值集
- 在一组模板参数中插入任意数量的类型
- 我正在尝试插入一组类
- 我如何在OpenCL中插入一组预先计算的函数
- 将值从一个数组插入到另一个直接排序的数组
- HDF5:在数据集中插入一组字符串