c++中如何更改映射元素的值

C++ how to change value of a map element

本文关键字:元素 映射 何更改 c++      更新时间:2023-10-16

我有一个带有整数和我创建的类的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;
}