fork(5) download
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. #include <string.h>
  5. #include <functional>
  6.  
  7. using namespace std;
  8.  
  9. // Define comparator functor:
  10. struct functor_test
  11. {
  12. bool operator()(string const & lhs, string const & rhs)
  13. {
  14. return strncmp(lhs.c_str(), rhs.c_str(), 4) < 0;
  15. }
  16. };
  17.  
  18. // Define comparator function:
  19. bool function_test(string const & lhs, string const & rhs)
  20. {
  21. return strncmp(lhs.c_str(), rhs.c_str(), 4) < 0;
  22. }
  23.  
  24. int main() {
  25. // Define comparator lambda:
  26. auto lambda_test = [](string const & lhs, string const & rhs)
  27. {
  28. return strncmp(lhs.c_str(), rhs.c_str(), 4) < 0;
  29. };
  30.  
  31. // These are all valid ways to declare the key comparator :
  32.  
  33. //As a functor:
  34. // map<string, string, functor_test> map;
  35.  
  36. //As a function using a function reference type:
  37. // map<string, string, bool(&)(string const&, string const&)> map(function_test);
  38.  
  39. //As a function using a function pointer type:
  40. // map<string, string, bool(*)(string const&, string const&)> map(function_test);
  41.  
  42. //As a function using a function class type wrapper:
  43. // map<string, string, function<bool(string const&, string const&)>> map(function_test);
  44.  
  45. //As a predefined lambda:
  46. // map<string, string, decltype(lambda_test)> map(lambda_test);
  47.  
  48. //As a predefined lambda using a function class type wrapper:
  49. // map<string, string, function<bool(string const&, string const&)>> map(lambda_test);
  50.  
  51. //As a lambda using a function class type wrapper:
  52. map<string, string, function<bool(string const&, string const&)>> map(
  53. [](string const & lhs, string const & rhs)
  54. {
  55. return strncmp(lhs.c_str(), rhs.c_str(), 4) < 0;
  56. });
  57.  
  58. map["test"] = "Foo";
  59. map["blah"] = "Drei";
  60. map["fayh"] = "Najh";
  61.  
  62. std::cout << map.find("test123")->second << endl; // Should output 'Foo'
  63. std::cout << map.find("test_2165")->second << endl; // Should output 'Foo' as well
  64. if (map.find("tes") == map.end())
  65. {
  66. cout << "Not found" << endl;
  67. }// Key not found
  68. std::cout << map.find("fayh_TK_Ka")->second << endl; // 'Najh'
  69.  
  70. return 0;
  71. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Foo
Foo
Not found
Najh