This new API ticks a few boxes for our daily programming. Think of the scenario that insert into the container if the key does not exist and update the value if it does exist. Before C++17 it has to use the combination of the following 3 calls as shown in Figure 1.
- find
- insert/emplace
- operator []
Figure 1. Implementation before C++17 |
Note: emplace() is recommended other than insert() for better performance.
The reason why not use operator [] directly, please refer to Item 24 in [1]. There Scott Meyer has detailed discussion about the performance between operator [] and insert.
2. C++17
From C++17 on the solutions shown in Figure 1 can be replace with this new API - insert_or_assign() as shown in Figure 2.
Figure 2. Implementation in C++17 with the New API |
I have looked at the assembly for the code under VS2015 and this is no performance penalty. Therefore feel free and happy to use.
Bibliography:
[1] Scott Meyers, Effectie STL 50 Specific Ways to Improve Your Use of the Standard Template Library