fork download
  1. #include <iostream>
  2. #include <map>
  3. using namespace std;
  4.  
  5. struct CompareString
  6. {
  7. using is_transparent = void;
  8.  
  9. bool operator()(const std::string& l, const string& r) const
  10. {
  11. return l.compare(r) < 0;
  12. }
  13.  
  14. template<typename T>
  15. bool operator()(const std::string& l, const T& r) const
  16. {
  17. return l.compare(r) < 0;
  18. }
  19.  
  20. template<typename T>
  21. bool operator()(const T& l, const std::string& r) const
  22. {
  23. return r.compare(l) > 0;
  24. }
  25. };
  26.  
  27. using StrStrMap = std::map<std::string,std::string, CompareString>;
  28.  
  29. template<typename K>
  30. const std::string* findPtr(const StrStrMap& c, const K& k) {
  31. auto iter = c.find(k);
  32. if (iter == c.end()) return nullptr;
  33. return &iter->second;
  34. }
  35.  
  36. const std::string& fromPtr(const std::string* s) {
  37. static const std::string def{"(null)"};
  38. if (!s) return def;
  39. return *s;
  40. }
  41.  
  42.  
  43. int main() {
  44. StrStrMap m{{"abc", "123"}, {"def", "456"}};
  45. const char kctrl1[] = "abc";
  46. const std::string kstd1 = "abc";
  47.  
  48. cout << __LINE__ << " " << fromPtr(findPtr(m, kstd1)) << endl;
  49. cout << __LINE__ << " " << fromPtr(findPtr(m, kctrl1)) << endl;
  50.  
  51. auto it = m.find(kstd1);
  52. if (it != m.end()) cout << it->second << endl;
  53.  
  54. return 0;
  55. }
Success #stdin #stdout 0s 4312KB
stdin
Standard input is empty
stdout
48 123
49 123
123