fork download
  1. #include <iostream>
  2.  
  3.  
  4. #include <vector>
  5.  
  6. template <class Element>
  7. class ObjectPool
  8. {
  9.  
  10. private:
  11. size_t activeElements;
  12. std::vector<Element> elements;
  13.  
  14. public:
  15. ObjectPool(size_t maxElements)
  16. {
  17. activeElements = 0;
  18. elements.resize(maxElements);
  19. }
  20.  
  21. size_t size() const
  22. {
  23. return activeElements;
  24. }
  25.  
  26. Element& at(size_t index)
  27. {
  28. if (index >= activeElements) {
  29. throw std::out_of_range("System: element requested is not active.");
  30. }
  31. return elements.at(index);
  32. }
  33.  
  34. const Element& at(size_t index) const
  35. {
  36. if (index >= activeElements) {
  37. throw std::out_of_range("System: element requested is not active.");
  38. }
  39. return elements.at(index);
  40. }
  41.  
  42. Element& back()
  43. {
  44. if (activeElements <= 0) {
  45. throw std::out_of_range("System: number of active elements is zero.");
  46. }
  47. return elements.at((size_t)(activeElements - 1));
  48. }
  49.  
  50. const Element& back() const
  51. {
  52. if (activeElements <= 0) {
  53. throw std::out_of_range("System: number of active elements is zero.");
  54. }
  55. return elements.at((size_t)(activeElements - 1));
  56. }
  57.  
  58. void addBackElement()
  59. {
  60. if (activeElements < elements.size()) {
  61. activeElements++;
  62. }
  63. else
  64. {
  65. throw std::out_of_range("System: maximum limit of elements in the system exceeded.");
  66. }
  67. }
  68.  
  69. void deleteElement(size_t index)
  70. {
  71. if (index >= activeElements) {
  72. throw std::out_of_range("System: element requested is not active.");
  73. }
  74. activeElements--;
  75. swapElements(activeElements, index);
  76. }
  77.  
  78. void resize(size_t maxElements)
  79. {
  80. elements.resize(maxElements);
  81. }
  82.  
  83. private:
  84. void swapElements(size_t i, size_t j)
  85. {
  86. std::swap(elements.at(i), elements.at(j));
  87. }
  88. };
  89.  
  90.  
  91. struct Laugh {
  92. Laugh() {
  93. std::cout << "Ha";
  94. }
  95. };
  96.  
  97.  
  98. int main() {
  99. ObjectPool<Laugh> pool(3);
  100. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
HaHaHa