Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- typedef struct {
- size_t size;
- size_t capacity;
- int*data;
- } Vector;
- Vector*NewVector()
- {
- Vector*vector=malloc(sizeof(Vector));
- if (!vector)
- {
- printf("Failed to Create Vector\n");
- return;
- }
- vector->data=NULL;
- vector->size=0;
- vector->capacity=1;
- return vector;
- }
- void push_back(Vector*vector, int value)
- {
- if (!vector->data)
- {
- int*newdata=malloc(vector->capacity*sizeof(int));
- if (!newdata)
- {
- printf("Failed Malloc\n");
- return;
- }
- vector->data=newdata;
- } else if (vector->capacity<=vector->size)
- {
- int*newdata=realloc(vector->data,vector->capacity*2*sizeof(int));
- if (!newdata)
- {
- printf("Failed to Realloc\n");
- return;
- }
- vector->capacity*=2;
- vector->data=newdata;
- }
- vector->data[vector->size++]=value;
- }
- void pop_back(Vector*vector)
- {
- if (vector->size == 0)
- {
- printf("Unable to Pop_back\n");
- return;
- }
- vector->size--;
- }
- void Resize(Vector*vector, int cursize)
- {
- if (cursize < 0)
- {
- printf("Invaild input Please Input More\n");
- return;
- }
- int*newdata=realloc(vector->data,cursize*sizeof(int));
- if (!newdata)
- {
- printf("Unable to Resize .. Realloc Failure");
- return;
- }
- vector->data=newdata;
- vector->size=(vector->size>(size_t)cursize)?cursize:vector->size;
- vector->capacity=cursize;
- }
- void ClearDataVector(Vector*vector)
- {
- free(vector->data);
- vector->data=NULL;
- vector->size=0;
- vector->capacity=1;
- }
- int main()
- {
- Vector*vector=NewVector();
- if (!vector) return 1;
- push_back(vector, 1);
- for (int i =0;i<=10;i++)
- {
- if (i % 2 == 0)
- {
- push_back(vector, i);
- }
- }
- for (int j =0;j<vector->size;j++)
- {
- printf("The Index Number %d of Vector Value IS : %d\n", j, vector->data[j]);
- }
- pop_back(vector);
- printf("And This is After pop_back\n");
- for (int j =0;j<vector->size;j++)
- {
- printf("The Index Number %d of Vector Value IS : %d\n", j, vector->data[j]);
- }
- ClearDataVector(vector);
- free(vector);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement