C++ 试图将_推回到列表上。C++;

C++ 试图将_推回到列表上。C++;,c++,C++,当我试图使用列表上的push_-back方法时,我遇到了一个编译器错误 这是我的密码: // Point iterator to the proper warehouse. set<cs3505::warehouse>::iterator curr_warehouse = warehouses.find(warehouse); // Insert new inventory_item into the warehouse. // Create a copy of today's

当我试图使用列表上的push_-back方法时,我遇到了一个编译器错误

这是我的密码:

// Point iterator to the proper warehouse.
set<cs3505::warehouse>::iterator curr_warehouse = warehouses.find(warehouse);

// Insert new inventory_item into the warehouse.

// Create a copy of today's date, and increment it.
cs3505::date exp_date = current_date;
exp_date.increment(curr_food.get_shelf_life());

// Create a new inventory item.
cs3505::inventory_item new_item(curr_food, exp_date);
// Set the quantity of the new item.
new_item.set_quantity(qty);

// Now insert the item.
// Adding new items being at the end ensures the oldest items will be at the 
// beginning of the list.
(*curr_warehouse).inventory.push_back(new_item);

我还有一个自定义仓库类,它有一个列表。我正在尝试将一个库存项目添加到该列表中。

这里的错误是因为您忽略了一个
const
限定符。这是因为集合返回的迭代器必须是常量。由于集合中的所有元素都必须是唯一的,所以存在此限制;通过迭代器更改集合中元素的值可能会破坏此约定

我无法立即找到确切的参考(SGI对
std::set
的参考没有提到这一点),因此我将链接到另一篇Stackoverflow文章,解释如下:

编辑:找到了

是的类型,表示值与键相同。下面一段总结了这一点:

类型X::iterator和X::const_iterator必须是相同的类型。也就是说,简单的关联容器不提供可变迭代器

这确实意味着我的第一段在技术上有点错误。这并不是为了确保不会将集合的元素从其下方更改为相同的值,而是仅仅通过设计。这实际上是“键是不可变的”这一基本概念不变的副作用


尽管如此,我还是将其保留在那里,以避免对其进行重大编辑。

此代码是否驻留在常量成员函数中?new_item是我要添加到列表中的新库存项,但其类型是什么?你能发布更多的代码吗?这个代码在一个主方法中。另外,
(*curr\u warehouse)的类型是什么。存货
/*
 * An inventory item which includes a food item, an expiration date,
 * and quantity.
 */

#include "inventory_item.h"
#include "date.h"
#include "food_item.h"

namespace cs3505
{
// inventory_item definitions

/*
 * Constructs an inventory item.
 */
inventory_item::inventory_item(food_item &item, date &exp_date)
{
    this->item = item;
    this->expiration_date = exp_date;
    this->quantity = 0;
}

/*
 * Destructs a food item.
 */
inventory_item::~inventory_item() { }

/*
 * Returns this inventory item's food item.
 */
food_item inventory_item::get_food_item()
{
    return this->item;
}

/*
 * Returns the expiration date for this inventory item.
 */
date inventory_item::get_exp_date()
{
    return this->expiration_date;
}

/*
 * Returns the quantity of this inventory item.
 */
int inventory_item::get_quantity()
{
    return this->quantity;
}

/*
 * Sets the quantity of this food item.
 */
void inventory_item::set_quantity(int change)
{
    this->quantity = change;
}
}