wbooze

correct

Mar 14th, 2022
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. // C++ implementation of Dynamic Array
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. template <class T>
  6. class DynamicArray {
  7. private:
  8. T *list;
  9. int max_size;
  10. int length;
  11. public:
  12. DynamicArray() {
  13. // initially allocate a single memory block
  14. max_size = 1;
  15. list = new T[max_size];
  16. length = 0;
  17. }
  18.  
  19. // insert a new item to the end of the list
  20. void add(T item) {
  21. if (isFull()) {
  22. // create temporary list with double size
  23. max_size = 2 * max_size;
  24. T *temp_list = new T[2* max_size];
  25.  
  26. // move all the elements to the temporary list
  27. for (int i = 0; i < length; i++) {
  28. temp_list[i] = list[i];
  29. }
  30.  
  31. // delete the old list
  32. delete [] list;
  33.  
  34. // rename temp list
  35. list = temp_list;
  36. }
  37.  
  38. // add the new item at the end of the list
  39. list[length] = item;
  40. length++;
  41. }
  42.  
  43. void printList() {
  44. for (int i = 0; i < length; i++) {
  45. cout<<list[i]<<' ';
  46. }
  47. cout<<endl;
  48. }
  49.  
  50. // check if the list is full
  51. bool isFull() {
  52. return length == max_size;
  53. }
  54.  
  55. ~DynamicArray() {
  56. delete [] list;
  57. }
  58.  
  59.  
  60. };
  61.  
  62. int main() {
  63. DynamicArray<char> list;
  64. list.add('1');
  65. list.add('2');
  66. list.add('3');
  67. list.add('4');
  68. list.add('5');
  69. list.add('6');
  70. list.add('7');
  71. list.add('8');
  72. list.add('9');
  73. list.printList();
  74. return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment