fork download
  1. #include "iostream"
  2. using namespace std;
  3. template<class T>
  4. class vector {
  5. private:
  6. T* ptr;
  7. int sz;
  8. int capacity;
  9. public:
  10. vector()
  11. {
  12. ptr = new T[1];
  13. sz = 0;
  14. capacity = 1;
  15. }
  16. vector(int s)
  17. {
  18. capacity = s;
  19. sz = 0;
  20. ptr = new T[s];
  21. }
  22.  
  23. ~vector()
  24. {
  25. if (ptr)delete ptr;
  26. }
  27. T operator[](int n)
  28. {
  29. if (n >= sz) {
  30. cout << "Khong ton tai" << endl;
  31. }
  32. else
  33. {
  34.  
  35. return ptr[n];
  36. }
  37. }
  38. int size()
  39. {
  40. return sz;
  41. }
  42. int getCapacity()
  43. {
  44. return capacity;
  45. }
  46. void reserve() // tự động thêm dung lượng
  47. {
  48. int newalloc = this->capacity * 2;
  49. this->capacity = newalloc;
  50. T* temp = new T[newalloc];
  51. for (int i = 0; i < this->sz; i++)
  52. {
  53. temp[i] = this->ptr[i];
  54. }
  55. if (this->ptr) { delete[] this->ptr; }
  56. this->ptr = temp;
  57. }
  58. void push_back(T elem)
  59. {
  60. if (sz == capacity)
  61. {
  62. reserve();
  63. this->ptr[sz] = elem;
  64. sz = sz + 1;
  65. }
  66. else
  67. {
  68. this->ptr[sz] = elem;
  69. sz = sz + 1;
  70. }
  71. }
  72. T pop_back()
  73. {
  74. T temp = this->ptr[sz-1];
  75. this->ptr[sz-1] = 0;
  76. sz = sz - 1;
  77. return temp;
  78.  
  79. }
  80. void print()
  81. {
  82. //cout << "Capacity: " << capacity << endl;
  83. for (int i = 0; i < sz; i++)
  84. {
  85. cout << ptr[i] << " ";
  86. }
  87. cout << endl;
  88. }
  89. // other methods
  90. };
  91. int main()
  92. {
  93. vector<int> a;
  94. a.push_back(1);
  95. a.push_back(2);
  96. a.push_back(3);
  97. a.push_back(4);
  98. a.push_back(5);
  99. a.push_back(6);
  100. int temp1 = a.pop_back();
  101. int temp2 = a.pop_back();
  102. cout << "Poped items: " << temp1 << " " << temp2 << endl;
  103. cout << "Items in vector: "; a.print();\
  104. cout << "Take out a value in vector: "<< a[0] << endl;
  105. cout << "Take out a value in vector: "<< a[10];
  106. }
Runtime error #stdin #stdout 0s 5460KB
stdin
Standard input is empty
stdout
Poped items: 6 5
Items in vector: 1 2 3 4 
Take out a value in vector: 1
Take out a value in vector: Khong ton tai