fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. #include <utility>
  5. #include <algorithm>
  6. using namespace std;
  7.  
  8. map<string, int> m = {{"hello", 1}, {"world", 2}};
  9.  
  10. class notFound
  11. { };
  12.  
  13. string findFromInt(const int& val)
  14. {
  15. map<string,int>::iterator it = m.begin();
  16. while(it != m.end())
  17. {
  18. if(it->second == val)
  19. return it->first;
  20.  
  21. it++;
  22. }
  23. throw new notFound();
  24. }
  25.  
  26. int findFromString(const string& str)
  27. {
  28. map<string,int>::iterator it = m.begin();
  29. while(it != m.end())
  30. {
  31. if(it->first.compare(str) == 0)
  32. return it->second;
  33.  
  34. it++;
  35. }
  36. throw new notFound();
  37. }
  38.  
  39.  
  40. int main() {
  41.  
  42.  
  43. int findVal = 2;
  44. try {
  45. string str = findFromInt(findVal);
  46.  
  47. cout << "found: " << str;
  48. } catch(notFound *obj) {
  49. cout << "Value not found";
  50. }
  51.  
  52.  
  53. string findStr = "hgggllo";
  54. try {
  55. int val = findFromString(findStr);
  56.  
  57. cout << "found: " << val;
  58. } catch(notFound *obj) {
  59. cout << "Value not found";
  60. }
  61.  
  62.  
  63.  
  64.  
  65. return 0;
  66. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
found: worldValue not found