Advertisement
OMEGAHEAD_MonkoX

IntArray

Nov 19th, 2020
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class intArray
  6. {
  7. private:
  8. int size, capacity, *a;
  9. public:
  10. intArray(int n = 0, int val = 0);
  11. intArray(const intArray &);
  12. ~intArray();
  13. void push_back(int val);
  14. intArray & operator = (const intArray &);
  15. };
  16.  
  17. intArray::intArray(int n, int val)
  18. {
  19. a = nullptr;
  20. capacity = size = 0;
  21.  
  22. if(n > 0){
  23. a = new int[n];
  24. capacity = size = n;
  25. for(int i = 0; i < size; ++i)
  26. a[i] = val;
  27. }
  28. }
  29.  
  30. intArray::intArray(const intArray & src)
  31. {
  32. a = nullptr;
  33. capacity = size = 0;
  34.  
  35. if(src.size > 0){
  36. a = new int[src.size];
  37. capacity = size = src.size;
  38. for(int i = 0; i < size; ++i)
  39. a[i] = src.a[i];
  40. }
  41. }
  42.  
  43. intArray::~intArray()
  44. {
  45. if(capacity > 0)
  46. delete [] a;
  47. }
  48.  
  49. intArray & intArray::operator = (const intArray & src)
  50. {
  51. if(capacity < src.capacity){
  52. if(capacity > 0)
  53. delete [] a;
  54. a = new int[src.capacity];
  55. capacity = src.size;
  56. }
  57. size = src.size;
  58. for(int i = 0; i < size; ++i)
  59. a[i] = src.a[i];
  60. }
  61.  
  62. void intArray::push_back(int val)
  63. {
  64. if(size == capacity)
  65. {
  66. int new_capacity = capacity > 0 ? 2 * capacity : 1;
  67. int * new_a = new int[new_capacity];
  68. for(int i = 0; i < size; ++i)
  69. new_a[i] = a[i];
  70. delete [] a;
  71. a = new_a;
  72. capacity = new_capacity;
  73. }
  74. a[size++] = val;
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement