fork download
  1. #include <algorithm>
  2. #include <iomanip>
  3. #include <iostream>
  4. #include <map>
  5. #include <memory>
  6.  
  7.  
  8. class Base {
  9. public:
  10. Base(int v) : id(v) {};
  11. int id;
  12. };
  13.  
  14. class Derived : public Base {
  15. public:
  16. Derived(int v) : Base(v) {};
  17. };
  18.  
  19.  
  20. struct Less_id
  21. {
  22. bool operator() (const std::shared_ptr<Derived> &lhs, const std::shared_ptr<Derived> &rhs) const
  23. {
  24. return lhs->id < rhs->id;
  25. }
  26. };
  27.  
  28. typedef std::map<std::shared_ptr<Derived>, double, Less_id> Map;
  29.  
  30. Map::const_iterator find_base(const Map &map, const std::shared_ptr<Base> &base)
  31. {
  32. auto it = std::lower_bound(
  33. map.begin(), map.end(), base,
  34. [](const Map::value_type &lhs, const std::shared_ptr<Base> &rhs)
  35. { return lhs.first->id < rhs->id; }
  36. );
  37. if (it != map.end() && it->first->id == base->id)
  38. return it;
  39. else
  40. return map.end();
  41. }
  42.  
  43.  
  44.  
  45.  
  46.  
  47. int main()
  48. {
  49. Map m;
  50. m.insert(std::make_pair(std::make_shared<Derived>(1), 10));
  51. m.insert(std::make_pair(std::make_shared<Derived>(3), 30));
  52. m.insert(std::make_pair(std::make_shared<Derived>(4), 40));
  53. m.insert(std::make_pair(std::make_shared<Derived>(2), 20));
  54.  
  55. auto b3 = std::make_shared<Base>(3);
  56. auto it = find_base(m, b3);
  57. std::cout << it->second << '\n';
  58.  
  59. auto b5 = std::make_shared<Base>(5);
  60. it = find_base(m, b5);
  61. std::cout << std::boolalpha << (it == m.end()) << '\n';
  62.  
  63. return 0;
  64. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
30
true