c++中如何更改映射元素的值
C++ how to change value of a map element
我有一个带有整数和我创建的类的map。现在我需要改变列表中每个元素的整数。
我是这样想的:
std::map<int, Product> ProductList; //This is filled somewhere and can be accessed in my function
void remove()
{
std::map<int, Product>::iterator it = ProductList.begin();
for(; it != ProductList.end(); it++)
{
it->first = it->first - 1;
}
}
现在编译器说
错误:只读成员'
std::pair<const int, Product>::first
'赋值
我做错了什么?我需要从每个元素的整数中减去1
不能这样修改映射的键;该映射必须在内部重新排序元素,因此您应该创建一个新映射并将其与旧映射交换。
void remove()
{
typedef std::map<int, Product> ProductMap;
ProductMap shifted;
ProductMap::const_iterator it = ProductList.begin();
ProductMap::const_iterator end = ProductList.end();
for(; it != end; ++it)
shifted.insert(std::pair<int, Product>(it->first - 1, it->second));
ProductList.swap(shifted);
}
你不能那样做。您正在尝试修改映射中元素的键。该键解锁该值,因此该值被该键解锁。如何用不同的键解锁相同的值?
您正在使用映射,因为很容易通过键获取值。但是你试图使用键作为索引,这是不可能的,这是一个不同的数据结构。
我认为应该为元素使用vector,为键使用vector,或者为map的临时副本使用vector。如果你能给我更多的信息,告诉我你为什么要这样做,那么也许我也可以更具体地提出解决方案。
您需要在映射中插入新的配对,并擦除旧的配对。最好创建一个新映射:
std::map<int,Product> oldProductList;
std::map<int,Product> newProductList;
std::map<product,int>::iterator it = iksProductList.begin();
for(; it != ProductList.end(); it++)
{
newProductList[it->first - 1] = it->second;
}
相关文章:
- 如何从存储在std::映射中的std::集中删除元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 删除映射和分割错误中的一个过去结束元素
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- C++映射不删除元素
- 打印无序映射的第二个元素,即集合
- 更改多重映射容器中所有元素的键值
- C++ 将元素分配给映射值时访问错误
- 类中的 C++ 全局映射,不要打印 map 元素
- 如何将元素插入和迭代到这种映射.C++
- 将数组的元素插入映射的时间复杂度是多少?
- 如何检查映射值中是否存在元素
- 常量映射和常量元素映射之间的区别
- 映射C++按值排序和插入元素
- 如何为映射和priority_queue编写比较器,其中元素是二维数组
- 访问range_expression中的嵌套元素会返回不完整的映射(段错误)
- 在映射中插入更多元素后,指向 QMap 中元素的指针是否仍然有效?
- 遍历 STL 映射(集/多集)的最佳方法,同时元素可能会在循环期间被删除并重新插入?
- 无法将元素添加到 STL 映射
- 索引标准/提升::按结构元素映射