How do I use try_emplace and insert_or_assign with std::map?

In C++, the `std::map` container provides several methods for inserting or updating elements. Two useful methods introduced in C++17 are `try_emplace` and `insert_or_assign`. Here's an overview of how to use these methods:

Using try_emplace

The `try_emplace` method constructs an element in-place if the key does not already exist in the map. If the key already exists, the method does not alter the map.

Using insert_or_assign

The `insert_or_assign` method either inserts a new element or updates the value of an existing key in the map. If the key is already present, its value is updated; otherwise, a new key-value pair is added.

Example

#include <iostream> #include <map> int main() { std::map myMap; // Using try_emplace myMap.try_emplace(1, "One"); myMap.try_emplace(1, "Uno"); // Does not insert, as key '1' already exists // Using insert_or_assign myMap.insert_or_assign(2, "Two"); myMap.insert_or_assign(2, "Dos"); // Updates value for key '2' // Print the map contents for (const auto& pair : myMap) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; }

C++ std::map try_emplace insert_or_assign C++17 key-value pairs map operations