Anas
Anas

Reputation: 379

Map key and value initialization from a variable

I am having hard time initializing a map (both key and value) from variables that are calculated in the code. such as the following example:

int a = 5;
int b = 3;
map<int, int> order;
order[(a)] = b;

I am trying to have the variable a as the key and the variable b as the value. Am I allow to do that ?

Upvotes: 1

Views: 1858

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

"Am I allow to do that ?"

Yes of course you can do that (see std::map::operator[] please). It's perfectly fine (though the parenthesis for (a) are superfluous). The value of b will be inserted into the map properly for key a, no matter if it existed before (in this case b will just replace the already existing associated value).

The case you should take care of is trying to access the std::map by key value, without having a value inserted in 1st place, like

int storedValue = order[a];

In this case a default initialized entry for order[a] will be created, and that's not what you want it to be in most of the use cases.

Upvotes: 2

Related Questions