fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4. #include <memory>
  5.  
  6. struct entity { //Simple struct of data.
  7. bool alive;
  8. float data;
  9. };
  10.  
  11. class manager {
  12. std::vector<std::shared_ptr<entity>> vec;
  13. public:
  14.  
  15. //Reserves initial_amount of entities
  16. explicit manager(size_t initial_amount) { vec.reserve(initial_amount); }
  17.  
  18. std::weak_ptr<entity> create(float f) {
  19. vec.push_back(std::make_unique<entity>(entity{true, f}));
  20. return vec.back();
  21. }
  22.  
  23. void refresh() {
  24. vec.erase(std::remove_if(vec.begin(), vec.end(),
  25. [](const auto& ent) {return !ent->alive;}),
  26. vec.end());
  27. }
  28.  
  29. void grow(size_t n) { vec.reserve(n); }
  30.  
  31. void print() const { //Prints all alive entities.
  32. for (const auto& ent : vec)
  33. std::cout << ent->data << " ";
  34. std::cout << std::endl;
  35. }
  36. };
  37.  
  38. int main() {
  39. manager c(10);
  40. auto d1 = c.create(5.5);
  41. auto d2 = c.create(10.5);
  42. auto d3 = c.create(7.5);
  43.  
  44. // Correct behavior
  45. if (auto e = d1.lock()) std::cout << e->data << std::endl; else std::cout << "Die\n"; // 5.5
  46. if (auto e = d2.lock()) std::cout << e->data << std::endl; else std::cout << "Die\n"; // 10.5
  47. if (auto e = d3.lock()) std::cout << e->data << std::endl; else std::cout << "Die\n"; // 7.5
  48. std::cout << std::endl;
  49.  
  50. if (auto e = d2.lock()) e->alive = false; // "Kill" the entity
  51. c.refresh(); // removes all dead entities.
  52.  
  53. if (auto e = d1.lock()) std::cout << e->data << std::endl; else std::cout << "Die\n"; // 5.5
  54. if (auto e = d2.lock()) std::cout << e->data << std::endl; else std::cout << "Die\n"; // Die
  55. if (auto e = d3.lock()) std::cout << e->data << std::endl; else std::cout << "Die\n"; // 10.5
  56. std::cout << std::endl;
  57.  
  58. c.print(); // Correct behavior, prints only alive entities.
  59. std::cout << std::endl;
  60.  
  61. if (auto e = d3.lock()) e->data = 6.5; // Trying to change the value of d3,
  62. // which should still be alive.
  63. c.print();
  64. std::cout << std::endl;
  65.  
  66. c.grow(10000);
  67.  
  68. if (auto e = d1.lock()) std::cout << e->data << std::endl; else std::cout << "Die\n"; // 5.5
  69. if (auto e = d2.lock()) std::cout << e->data << std::endl; else std::cout << "Die\n"; // Die
  70. if (auto e = d3.lock()) std::cout << e->data << std::endl; else std::cout << "Die\n"; // 6.5
  71. }
  72.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
5.5
10.5
7.5

5.5
Die
7.5

5.5 7.5 

5.5 6.5 

5.5
Die
6.5