#include <iostream>
#include <map>
#include <stdexcept>
template <typename K, typename V>
V& map_at(std::map<K, V>& a_map, K const& a_key)
{
typename std::map<K, V>::iterator i = a_map.find(a_key);
if (a_map.end() == i)
{
throw std::out_of_range("map_at()");
}
return i->second;
}
int main()
{
try
{
std::map<int, int> m;
m[4] = 4;
std::cout << map_at(m, 4) << std::endl;
map_at(m, 5);
}
catch (std::out_of_range const& e)
{
std::cout << "out_of_range: " << e.what() << std::endl;
}
try
{
std::map<std::string, char> m;
m["hello"] = 'c';
std::cout << map_at(m, std::string("hello")) << std::endl;
map_at(m, std::string("world"));
}
catch (std::out_of_range const& e)
{
std::cout << "out_of_range: " << e.what() << std::endl;
}
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8bWFwPgojaW5jbHVkZSA8c3RkZXhjZXB0PgoKdGVtcGxhdGUgPHR5cGVuYW1lIEssIHR5cGVuYW1lIFY+ClYmIG1hcF9hdChzdGQ6Om1hcDxLLCBWPiYgYV9tYXAsIEsgY29uc3QmIGFfa2V5KQp7CiAgICB0eXBlbmFtZSBzdGQ6Om1hcDxLLCBWPjo6aXRlcmF0b3IgaSA9IGFfbWFwLmZpbmQoYV9rZXkpOwogICAgaWYgKGFfbWFwLmVuZCgpID09IGkpCiAgICB7CiAgICAgICAgdGhyb3cgc3RkOjpvdXRfb2ZfcmFuZ2UoIm1hcF9hdCgpIik7CiAgICB9CiAgICByZXR1cm4gaS0+c2Vjb25kOwp9CgppbnQgbWFpbigpCnsKICAgIHRyeQogICAgewogICAgICAgIHN0ZDo6bWFwPGludCwgaW50PiBtOwogICAgICAgIG1bNF0gPSA0OwogICAgICAgIHN0ZDo6Y291dCA8PCBtYXBfYXQobSwgNCkgPDwgc3RkOjplbmRsOwogICAgICAgIG1hcF9hdChtLCA1KTsKICAgIH0KICAgIGNhdGNoIChzdGQ6Om91dF9vZl9yYW5nZSBjb25zdCYgZSkKICAgIHsKICAgICAgICBzdGQ6OmNvdXQgPDwgIm91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