- C++17 STL Cookbook
- Jacek Galowicz
- 252字
- 2025-04-04 19:00:06
How it works...
The whole recipe revolves around the try_emplace function of std::map, which is a new C++17 addition. It has the following signature:
std::pair<iterator, bool> try_emplace(const key_type& k, Args&&... args);
Thus, the key being inserted is parameter k and the associated value is constructed from the parameter pack args. If we succeed in inserting the item, then the function returns an iterator, which points to the new node in the map, paired with a Boolean value being set to true. If the insertion was not successful, the Boolean value in the return pair is set to false, and the iterator points to the item with which the new item would clash.
This characteristic is very useful in our case--when we see a billionaire from a specific country for the first time, then this country is not a key in the map yet. In that case, we must insert it, accompanied with a new counter being set to 1. If we did see a billionaire from a specific country already, we have to get a reference to its existing counter, in order to increment it. This is exactly what happened in step 6:
if (!success) {
iterator->second.second += 1;
}