Advertisement
SigmaBoy456

Vector C basic #7291

Feb 17th, 2025
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. typedef struct {
  5. size_t size;
  6. size_t capacity;
  7. int*data;
  8. } Vector;
  9.  
  10. Vector*NewVector()
  11. {
  12. Vector*vector=malloc(sizeof(Vector));
  13. if (!vector)
  14. {
  15. printf("Failed to Create Vector\n");
  16. return;
  17. }
  18. vector->data=NULL;
  19. vector->size=0;
  20. vector->capacity=1;
  21. return vector;
  22. }
  23.  
  24. void push_back(Vector*vector, int value)
  25. {
  26. if (!vector->data)
  27. {
  28. int*newdata=malloc(vector->capacity*sizeof(int));
  29. if (!newdata)
  30. {
  31. printf("Failed Malloc\n");
  32. return;
  33. }
  34. vector->data=newdata;
  35. } else if (vector->capacity<=vector->size)
  36. {
  37. int*newdata=realloc(vector->data,vector->capacity*2*sizeof(int));
  38. if (!newdata)
  39. {
  40. printf("Failed to Realloc\n");
  41. return;
  42. }
  43. vector->capacity*=2;
  44. vector->data=newdata;
  45. }
  46. vector->data[vector->size++]=value;
  47. }
  48.  
  49. void pop_back(Vector*vector)
  50. {
  51. if (vector->size == 0)
  52. {
  53. printf("Unable to Pop_back\n");
  54. return;
  55. }
  56. vector->size--;
  57. }
  58.  
  59. void Resize(Vector*vector, int cursize)
  60. {
  61. if (cursize < 0)
  62. {
  63. printf("Invaild input Please Input More\n");
  64. return;
  65. }
  66. int*newdata=realloc(vector->data,cursize*sizeof(int));
  67. if (!newdata)
  68. {
  69. printf("Unable to Resize .. Realloc Failure");
  70. return;
  71. }
  72. vector->data=newdata;
  73. vector->size=(vector->size>(size_t)cursize)?cursize:vector->size;
  74. vector->capacity=cursize;
  75. }
  76.  
  77. void ClearDataVector(Vector*vector)
  78. {
  79. free(vector->data);
  80. vector->data=NULL;
  81. vector->size=0;
  82. vector->capacity=1;
  83. }
  84.  
  85. int main()
  86. {
  87. Vector*vector=NewVector();
  88. if (!vector) return 1;
  89. push_back(vector, 1);
  90. for (int i =0;i<=10;i++)
  91. {
  92. if (i % 2 == 0)
  93. {
  94. push_back(vector, i);
  95. }
  96. }
  97. for (int j =0;j<vector->size;j++)
  98. {
  99. printf("The Index Number %d of Vector Value IS : %d\n", j, vector->data[j]);
  100. }
  101. pop_back(vector);
  102. printf("And This is After pop_back\n");
  103. for (int j =0;j<vector->size;j++)
  104. {
  105. printf("The Index Number %d of Vector Value IS : %d\n", j, vector->data[j]);
  106. }
  107. ClearDataVector(vector);
  108. free(vector);
  109. return 0;
  110. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement