fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <stdexcept>
  4.  
  5. template <typename K, typename V>
  6. V& map_at(std::map<K, V>& a_map, K const& a_key)
  7. {
  8. typename std::map<K, V>::iterator i = a_map.find(a_key);
  9. if (a_map.end() == i)
  10. {
  11. throw std::out_of_range("map_at()");
  12. }
  13. return i->second;
  14. }
  15.  
  16. int main()
  17. {
  18. try
  19. {
  20. std::map<int, int> m;
  21. m[4] = 4;
  22. std::cout << map_at(m, 4) << std::endl;
  23. map_at(m, 5);
  24. }
  25. catch (std::out_of_range const& e)
  26. {
  27. std::cout << "out_of_range: " << e.what() << std::endl;
  28. }
  29.  
  30. try
  31. {
  32. std::map<std::string, char> m;
  33. m["hello"] = 'c';
  34. std::cout << map_at(m, std::string("hello")) << std::endl;
  35. map_at(m, std::string("world"));
  36. }
  37. catch (std::out_of_range const& e)
  38. {
  39. std::cout << "out_of_range: " << e.what() << std::endl;
  40. }
  41.  
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
4
out_of_range: map_at()
c
out_of_range: map_at()