fork download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <cstdlib>
  4. #include <cstdio>
  5. #include <cmath>
  6. #include <algorithm>
  7. using namespace std;
  8.  
  9. template <class T>
  10. class Set
  11. {
  12. public:
  13. T *p; // change
  14. int n;
  15. Set(){ p=nullptr; n=0;
  16. };
  17. Set(int n)
  18. {
  19. this->n = n;
  20. p = new T[n]; // change
  21. }
  22. ~Set()
  23. {
  24. if(p) delete []p;
  25. }
  26. void setValues(T k[],int l) // change signature
  27. {
  28. if (n!=l) { // if the size is the same, we'll reuse p, if not:
  29. delete[] p; // avoid the memory to leek
  30. p= new T[l]; // start with a fresh memory
  31. n = l; // define new length
  32. }
  33. for (int i=0; i<l; i++)
  34. p[i]=k[i]; // copy array elements one by one
  35. }
  36. void add(T k)
  37. {
  38. auto p1 = p; // improvement
  39. p = new T[n+1];
  40. //p = p1; nooooooooo !!
  41. for (int i=0; i<n; i++)
  42. p[i]=p1[i];
  43. delete []p1; // no more leaking
  44.  
  45. p[n] = k;
  46. n++;
  47. }
  48. void remove(T k)
  49. {
  50. //int l =0;
  51. //auto p1 = p; // no need to reallocateimprovement
  52. //p = new T[n-1];
  53. int removed=0;
  54. for(int i=0,j=0;i<n;i++)
  55. if(p[i]!=k)
  56. {
  57. if (i!=j)
  58. p[j] = p[i];
  59. j++;
  60. }
  61. else removed++;
  62. n=n-removed;
  63. }
  64. void operator+(Set s)
  65. {
  66. for(int i=0;i<n;i++)
  67. p[i]+=s.p[i];
  68. }
  69. void operator-(Set s)
  70. {
  71. for(int i=0;i<n;i++)
  72. p[i]-=s.p[i];
  73. }
  74. void operator*(Set s)
  75. {
  76. for(int i=0;i<n;i++)
  77. p[i]*=s.p[i];
  78. }
  79. void show()
  80. {
  81. for(int i=0;i<n;i++)
  82. cout<<p[i]<<" | ";
  83. }
  84. };
  85. int main()
  86. {
  87. Set<int> s1,s2;
  88. int arr[]={0,2,3,4,3,6};
  89. int n=6;
  90. float arr2[]={0.5,12.1,1.7,23.15};
  91. char arr3[]={'a','h','m','k','c','e'};
  92. s1.setValues(arr,n); // <------------- here is error;
  93. s1.add(5);
  94. s1.remove(3);
  95. s1.show();
  96.  
  97. }
Success #stdin #stdout 0s 4560KB
stdin
Standard input is empty
stdout
0 | 2 | 4 | 6 | 5 |