5.4.4 Updating Maps

Like other data structures that use the [ ] operator, maps allow updates in the same way. With maps, it gets a little more tricky since the [ ] operator is also used to create new values.

Access vs Update vs Insert

When using the [ ] operator, you can do one of three things, access, update, or insert. If the key currently exists you will access it or update it with an assignment operator.

Take a look at this map:

map<string, int> people {{"James", 14}, {"Julie", 15}};

Map values:

James - 14
Julie - 15

You can access and update values with these statements:

// Access the value
cout << "James' age: << people["James"] << endl;

// Update the value
people["Julie"] =  14;

Map Values after this statement:

James - 14
Julie - 14

If the key doesn’t exist, the exact same sets of commands can be executed, but much different results.

// Access the value
cout << "Kyle's age: << people["Kyle"] << endl;

// Update the value
people["Karen"] =  14;

Map Values after this statement:

James - 14
Julie - 14
Kyle - 0
Karen - 14

Notice how the access in the print line created a new map entry with Kyle as the key and a default value of 0. Likewise, the access statement created a new entry with Karen as the key and a value of 14.

Update With .at()

Just like with the [ ] operator, the .at() can also be used to update values. As mentioned before, if you use the .at() and a value does not exist, it will throw an error.

Using the above example:

// Updates Karent to 15
people.at("Karen") =  15;

// Throws an error
people.at("Mikayla") = 14;

Shortcut Operators

Shortcut operators are also available for maps:

people["James"] ++; // add one to James
people["Julie] *= 2; // Double Julie
people["Karel"] ++; // Creates a new entry with a value of 1

Shortcuts work as expected, but notice in the last example how they can still be used to create new values and they perform the operation after the default value is created. You saw above that Kyle was created with a default value of 0, but since Karel is created with the incrementor, the value ends at 1.

Insert Function

You saw the basic insert command in an earlier example. Insert in maps actually works as it does for sets. There is a return pair with the first value being an iterator that points to the position of the element and the second value being a boolean as to whether the value was inserted.

map<string, int> people {{"James", 14}, {"Julie", 15}};

pair<map<string,int>::iterator, bool> rtn = 
        stock.insert(pair<string, int>("Kyle", 16));

cout << rtn.second << endl;

In the above example, the output will be 1 for true.

Last updated