fork(1) download
  1. // http://stackoverflow.com/questions/14917169/finding-an-element-in-a-shared-ptr-container/14917562#14917562
  2.  
  3. #include <vector>
  4. #include <memory>
  5. #include <algorithm>
  6. #include <iostream>
  7.  
  8. using namespace std;
  9.  
  10. struct Block
  11. {
  12. bool in_container(const vector<shared_ptr<Block>>& blocks)
  13. {
  14. auto end = blocks.end();
  15. return end != find_if(blocks.begin(), end,
  16. [this](shared_ptr<Block> const& i)
  17. { return i.get() == this; });
  18. }
  19. };
  20.  
  21. int main()
  22. {
  23. auto block1 = make_shared<Block>();
  24. auto block2 = make_shared<Block>();
  25.  
  26. vector<shared_ptr<Block>> blocks;
  27. blocks.push_back(block1);
  28.  
  29. block1->in_container(blocks) ?
  30. cout << "block1 is in the container\n" :
  31. cout << "block1 is not in the container\n";
  32.  
  33. block2->in_container(blocks) ?
  34. cout << "block2 is in the container\n" :
  35. cout << "block2 is not in the container\n";
  36.  
  37. return 0;
  38. }
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
block1 is in the container
block2 is not in the container