Davlog
Davlog

Reputation: 2238

C++ how to change value of a map element

I have a map with an integer and a class I made. Now I need to change the integer of each element in the list.

I thought about sth like this :

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

Now my compiler says

error: assignment of read-only member 'std::pair<const int, Product>::first'

What am I doing wrong? I need to subtract 1 from the integer of each element.

Upvotes: 1

Views: 11121

Answers (3)

Lajos Arpad
Lajos Arpad

Reputation: 76551

You can't do that. You are trying to modify the key of an element in the map. The key unlocks the value, so the value is unlocked by the key. How can you unlock the same value with a different key?

You are using a map, because it is easy to get the value by the key. But you are trying to use the key as an index, which is not possible, this is a different data structure.

I think you should use a vector for your elements, or a vector for your keys, or a temporary copy of the map. If you give me more information about why are you trying to do this, then maybe I can be more specific about the solution too.

Upvotes: 1

JRG
JRG

Reputation: 2135

You cannot modify the keys of the map like that; the map would have to reorder the elements internally, so you should create a new map and swap it with the old one.

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

Upvotes: 2

Bogatyr
Bogatyr

Reputation: 19323

You need to insert a new pair into the map, and erase the old one. It's probably best just to create a new map:

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

Upvotes: 0

Related Questions