Guest User

Untitled

a guest
Aug 15th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. Check if container of shared_ptr contains a pointer?
  2. std::list<SomeSharedPointer> items_;
  3. ...
  4. void Monitor::Update(Subject *subject)
  5. {
  6. if(subject == something_)
  7. {
  8. DoSomething();
  9. }
  10. else if
  11. ??
  12. // if subject is one of the objects in our collection then do something..
  13.  
  14. }
  15.  
  16. auto i = std::find_if(items_.begin(), items_.end(),
  17. [=](const SomeSharedPointer& x) { return x.get() == subject; });
  18.  
  19. if (i != c.end())
  20. {
  21. // Object found, and i is an iterator pointing to it
  22. }
  23.  
  24. typedef std::list<SomeSharedPtr> ObserverCollection;
  25.  
  26. // You can also add a const version if needed
  27. ObserverCollection::iterator find_observer(Subject* s)
  28. {
  29. return std::find_if(items_.begin(), items_.end(),
  30. [=](const SomeSharedPointer& x) { return x.get() == s; });
  31. }
  32.  
  33. auto i = find_observer(subject);
  34. if (i != items_.end())
  35. {
  36. // Object found
  37. }
  38.  
  39. if (find_observer(subject) != items_.end())
  40. {
  41. ...
  42. }
  43.  
  44. for (auto iter = items_.begin(); iter != items_.end(); ++iter)
  45. {
  46. if (subject == iter->get())
  47. {
  48. .. do stuff ..
  49. }
  50. }
  51.  
  52. enum State{ STATE_1, STATE_2 };
  53.  
  54. void Monitor::Update(Subject *subject)
  55. {
  56. switch( subject->getState() )
  57. {
  58. case STATE_1:
  59. // do something 1
  60. break;
  61. case STATE_2:
  62. // do something 2
  63. break;
  64. default:
  65. //error
  66. }
  67. }
Add Comment
Please, Sign In to add comment