#include <iostream>
#include <string>
#include <unordered_map>
int main()
{
// Create an unordered_map of three strings (that map to strings)
std::unordered_map<std::string, std::string> u = {
{"RED","#FF0000"},
{"GREEN","#00FF00"},
{"BLUE","#0000FF"}
};
// Helper lambda function to print key-value pairs
auto print_key_value = [](const auto& key, const auto& value) {
std::cout << "Key:[" << key << "] Value:[" << value << "]
";
};
std::cout << "Iterate and print key-value pairs of unordered_map, being
"
"explicit with their types:
";
for( const std::pair<const std::string, std::string>& n : u ) {
print_key_value(n.first, n.second);
}
std::cout << "
Iterate and print key-value pairs using C++17 structured binding:
";
for( const auto& [key, value] : u ) {
print_key_value(key, value);
}
// Add two new entries to the unordered_map
u["BLACK"] = "#000000";
u["WHITE"] = "#FFFFFF";
std::cout << "
Output values by key:
"
"The HEX of color RED is:[" << u["RED"] << "]
"
"The HEX of color BLACK is:[" << u["BLACK"] << "]
";
std::cout << "Use operator[] with non-existent key to insert a new key-value pair:
";
print_key_value("new_key", u["new_key"]);
std::cout << "
Iterate and print key-value pairs, using `auto`;
"
"new_key is now one of the keys in the map:
";
for( const auto& n : u ) {
print_key_value(n.first, n.second);
}
}