No viable overloaded error "=" with map key

I got this error when trying to do the following

Rellotge nclock(request, mclock);
if (oldclock < nclock) (iteratorValue[tasknum-1])->first = nclock;

      

iteratorValue is a map dictionary and the map key is the same type as nclock.

   Agenda.cc:65:70: error: no viable overloaded '='
                if (oldclock < nclock) (iteratorValue[tasknum-1])->first = nclock;

      

+3


source to share


1 answer


The element type in the dictionary std::map<Key, T>

is a pair as shown below.

using value_type = std::pair<const Key, T>;

      

Note that the key is a permanent element, it cannot be changed and there is a reason.

std :: map is a sorted associative container containing key-value pairs with unique keys . Keys are sorted using the Compare function. Search, delete, and insert operations have logarithmic complexity. Maps are usually implemented as red-black trees.



Pay attention to the highlighted points, they are the key for the reason why you cannot change the dictionary key.

  • Since it is a sorted container, using keys to order items for faster searches, by changing the key at any time, you break the container, because you end up invalidating all sorts.
  • By changing the key, you can duplicate key elements without the container's knowledge, which will violate the guarantee of unique keys.

If you need to change the key, you probably want to erase the old item from the map and insert another new key. You might want to change the value element associated with an existing key.

+5


source







All Articles