#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm> // transform
// ------------------------------------------------------------
// getCountryName
// Receives a 2-letter ISO country code and returns the
// corresponding country name.
//
// Uses an unordered_map for O(1) average lookup time.
// Input is normalized to uppercase to ensure consistent matching.
// Returns an empty string if the code is not found.
// ------------------------------------------------------------
std::string getCountryName(const std::string& alpha2)
{
// Static map: initialized once, reused efficiently
static const std::unordered_map<std::string, std::string> countryMap = {
{"US", "United States"},
{"GB", "United Kingdom"},
{"FR", "France"},
{"DE", "Germany"},
{"CA", "Canada"},
{"JP", "Japan"},
{"CN", "China"},
{"IN", "India"}
// Add more as needed
};
// Normalize input: trim not needed here, but uppercase is essential
std::string code = alpha2;
std::transform(code.begin(), code.end(), code.begin(), ::toupper);
// Lookup
auto it = countryMap.find(code);
return (it != countryMap.end()) ? it->second : "";
}
// ------------------------------------------------------------
// main
// Demonstrates the lookup function with several sample codes.
// ------------------------------------------------------------
int main()
{
std::string codes[] = {"US", "GB", "FR", "JP", "ZZ"}; // ZZ is intentionally invalid
for (const auto& code : codes)
{
std::string name = getCountryName(code);
if (!name.empty()) {
std::cout << code << " → " << name << "\n";
}
else {
std::cout << code << " → (invalid code)\n";
}
}
}
/*
run:
US → United States
GB → United Kingdom
FR → France
JP → Japan
ZZ → (invalid code)
*/