fork(1) download
  1. #include <memory>
  2. #include <deque>
  3.  
  4. template<class T,class size_type = std::size_t>
  5. class ArrayList{
  6. std::deque<std::shared_ptr<T>> Elements;
  7. std::deque<std::shared_ptr<T>> Removes;
  8. public:
  9. typedef T Type;
  10. typedef size_type SizeType;
  11. public:
  12. ArrayList(){}
  13. bool Push_Back(std::shared_ptr<T> Item){
  14. Elements.push_back(Item);
  15. return true;
  16. }
  17. bool Push_Back(T* Item){//i need user called new object. do not delete Item by your hand.
  18. std::shared_ptr<T> ptr = std::shared_ptr<T>(Item);
  19. Elements.push_back(ptr);
  20. return true;
  21. }
  22. bool Push_Back(const T& Item){
  23. std::shared_ptr<T> ptr = std::shared_ptr<T>(nullptr);
  24. if(Removes.size() != 0){
  25. ptr = Removes.back();
  26. Removes.pop_back();
  27. *ptr = Item;
  28. }else{
  29. //ptr = std::shared_ptr<T>(new T(Item));
  30. ptr= std::make_shared<T>(Item);
  31. }
  32.  
  33. Elements.push_back(ptr);
  34.  
  35. return true;
  36. }
  37. const size_type Size() const{
  38. return Elements.size();
  39. }
  40.  
  41. bool Erase(size_type Idx){
  42. Removes.push_back(Elements[Idx]);
  43. Elements.erase(Elements.begin()+Idx);
  44. return true;
  45. }
  46. bool GabageCollect(){
  47. Removes.clear();
  48. return true;
  49. }
  50.  
  51. T& operator [](size_type Idx){
  52. return *(Elements[Idx].get());
  53. }
  54. std::shared_ptr<T> GetShared(size_type Idx){
  55. return Elements[Idx];
  56. }
  57. };
  58.  
  59. #include <iostream>
  60. //#include "ArrayList.h"
  61.  
  62. template<class T = int>
  63. class TestObject{
  64. T i;
  65. public:
  66. TestObject(const T& Item):i(Item){
  67. std::cout<<"construct:"<<Item<<std::endl;
  68. }
  69. const T& Get(){ return i;}
  70. virtual ~TestObject(){
  71. std::cout<<"Destruct:"<<i<<std::endl;
  72. }
  73. };
  74.  
  75. int main(){
  76. typedef TestObject<int> TO;
  77. ArrayList<TO> Array;
  78.  
  79. for(int i=0;i<8;i++){
  80. Array.Push_Back(new TO(i));
  81. }
  82.  
  83. Array.Erase(3);
  84. Array.Erase(4);
  85. Array.Erase(5);
  86.  
  87. Array.Push_Back(TO(8));
  88. Array.Push_Back(new TO(9));
  89. Array.Push_Back(std::make_shared<TO>(10));
  90.  
  91. Array.GabageCollect();
  92.  
  93. for(int i=0;i<Array.Size();i++){
  94. std::cout<<Array[i].Get()<<std::endl;
  95. }
  96. return 0;
  97. }
Success #stdin #stdout 0s 2996KB
stdin
Standard input is empty
stdout
construct:0
construct:1
construct:2
construct:3
construct:4
construct:5
construct:6
construct:7
construct:8
Destruct:8
construct:9
construct:10
Destruct:3
Destruct:5
0
1
2
4
6
8
9
10
Destruct:0
Destruct:1
Destruct:2
Destruct:4
Destruct:6
Destruct:8
Destruct:9
Destruct:10