Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unordered_map insert with void (*)() as value is not working properly

I am using this unordered map:

typedef unordered_map <char, void (*)()> Keymap;
Keymap keys;

and trying to fill it with:

void assign(char key, void (*value)())
{
    if (keys[key] == NULL)
        keys.insert(Keymap::value_type(key, value));
    else
        keys[key] = value;
}

the instruction:

keys.insert(Keymap::value_type(key, value));

inserts the char into the key but value isn't initialized (NULL), so I have a map with ('s', NULL) instead of ('s', function_pointer).

The instruction keys[key] = value; is working properly.

Where is the error?

like image 735
chiarfe Avatar asked Dec 05 '25 06:12

chiarfe


1 Answers

This expression:

keys[key] == NULL

And in particular, the subexpression:

keys[key]

Has the side effect of inserting a new key-value pair in the map where key is the key, and the corresponding value is value-initialized. This is how operator [] for std::unordered_map is meant to work (see here).

This expression, on the other hand:

keys.insert(Keymap::value_type(key, value));

Will not insert the specified key-value pair in the map if one pair is already present for that key (see, for instance, here), and that value was just inserted when doing:

if (keys[key] == NULL)

So indeed all you want to do here is just:

void assign(char key, void (*value)())
{
    keys[key] = value;
}
like image 61
Andy Prowl Avatar answered Dec 07 '25 19:12

Andy Prowl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!