fork download
  1. #include <map>
  2. #include <algorithm>
  3. #include <iostream>
  4.  
  5. template<class Map, class KeyCompareType, class Iterator = typename Map::const_iterator>
  6. Iterator findInMap(const Map &map, const KeyCompareType &key) {
  7. typedef typename Map::value_type value_type;
  8. auto predicate = [](const value_type & entry, const KeyCompareType & key) {
  9. return entry.first < key;
  10. };
  11. Iterator it = std::lower_bound(map.begin(), map.end(), key, predicate);
  12. if (it != map.end()) {
  13. if (!(it->first == key))
  14. it = map.end();
  15. }
  16. return it;
  17. }
  18.  
  19. struct ClassA {
  20. int value;
  21. };
  22. bool operator==(const ClassA &a, const ClassA &b) {
  23. return a.value == b.value;
  24. }
  25. bool operator<(const ClassA &a, const ClassA &b) {
  26. return a.value < b.value;
  27. }
  28.  
  29. struct ClassB {
  30. int value;
  31. };
  32.  
  33. bool operator==(const ClassA &a, const ClassB &b) {
  34. return a.value == b.value;
  35. }
  36. bool operator<(const ClassA &a, const ClassB &b) {
  37. return a.value < b.value;
  38. }
  39.  
  40.  
  41.  
  42.  
  43. int main() {
  44. std::map<ClassA, int> foo;
  45. foo.insert({{1}, 1});
  46. foo.insert({{2}, 2});
  47. foo.insert({{3}, 3});
  48.  
  49. std::vector<ClassB> testCases = {{1}, {2}, {3}, {4}};
  50.  
  51. for (ClassB testCase : testCases) {
  52. std::cout << "Looking up " << testCase.value << " -> ";
  53. auto it = findInMap(foo, testCase);
  54. if (it == foo.end())
  55. std::cout << "Not found." << std::endl;
  56. else
  57. std::cout << "Found: " << it->second << std::endl;
  58. }
  59. }
  60.  
  61.  
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
Looking up 1 -> Found: 1
Looking up 2 -> Found: 2
Looking up 3 -> Found: 3
Looking up 4 -> Not found.