Advertisement
Guest User

Untitled

a guest
Mar 30th, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class VectorDouble {
  5. private:
  6. double* array;
  7. int max_count;
  8. int count;
  9. public:
  10. VectorDouble() {
  11. max_count = 50;
  12.  
  13. array = (double*)malloc(max_count * sizeof(double));
  14.  
  15. count = 0;
  16. }
  17.  
  18. VectorDouble(VectorDouble& v) {
  19. max_count = v.size();
  20. array = (double*)malloc(max_count * sizeof(double));
  21.  
  22. for (int i = 0; i < max_count; i++) {
  23. array[i] = v.value_at(i);
  24. }
  25. count = max_count;
  26. }
  27.  
  28. int size() {
  29. return count;
  30. }
  31.  
  32. void push_back(double d) {
  33. if (count == max_count) {
  34. max_count *= 2;
  35. double* newarr = (double*)malloc(max_count * sizeof(double));
  36.  
  37. for (int i = 0; i < count; i++) {
  38. newarr[i] = array[i];
  39. }
  40.  
  41. delete array;
  42. array = newarr;
  43. }
  44. array[count++] = d;
  45. }
  46.  
  47. void change_value_at(double d, int i) {
  48. array[i] = d;
  49. }
  50.  
  51. double value_at(int i) {
  52. return array[i];
  53. }
  54.  
  55. void resize(int num) {
  56. if (num == max_count) {
  57. count = max_count;
  58. return;
  59. }
  60.  
  61. double* newArray = (double*)malloc(num * sizeof(double));
  62. int temp = (count < num) ? count : num;
  63.  
  64. for (int i = 0; i < temp; i++) {
  65. newArray[i] = array[i];
  66. }
  67.  
  68. delete array;
  69. array = newArray;
  70. count = num;
  71. }
  72.  
  73. void reserve(int num) {
  74. if (num <= max_count) return;
  75. max_count = num;
  76. double* newarr = (double*)malloc(max_count * sizeof(double));
  77.  
  78. for (int i = 0; i < count; i++) {
  79. newarr[i] = array[i];
  80. }
  81.  
  82. delete array;
  83. array = newarr;
  84. }
  85. };
  86.  
  87. int main() {
  88. VectorDouble v;
  89. v.push_back(4.7);
  90. v.push_back(1992.4);
  91. v.push_back(842);
  92. v.push_back(.11);
  93.  
  94. VectorDouble v2;
  95.  
  96. for (int i = 0; i < 76; i++) { //Creating an array that is larger than max count to display it can still handle it by resizing
  97. v2.push_back(i);
  98. }
  99.  
  100. cout << "Size of v is: " << v.size() << endl;
  101. cout << "Size of v2 is: " << v2.size() << endl;
  102. cout << "V = ";
  103.  
  104. for (int i = 0; i < v.size(); i++) { //Printing contents of v
  105. cout << v.value_at(i) << " ";
  106. }
  107.  
  108. cout << endl;
  109.  
  110. v.change_value_at(56.1, 1); //Changing a value
  111.  
  112. for (int i = 0; i < v.size(); i++) { //Printing contents of v
  113. cout << v.value_at(i) << " ";
  114. }
  115.  
  116. cout << endl;
  117.  
  118. return 0;
  119. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement