#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <time.h>
typedef struct Vector {
int *data;
int size;
int length;
} Vec;
Vec *init(int n) {
Vec *v = (Vec *)malloc(sizeof(Vec));
v->data = (int *)malloc(sizeof(int) * n);
v->size = n;
v->length = 0;
return v;
}
int expand(Vec *v) {
if (!v) return 0;
int extr_size = v->size;
int *p = NULL;
while (extr_size) {
p = (int *)realloc(v->data, sizeof(int) * (v->size + extr_size));
if (p) break;
extr_size /= 2;
}
if (!extr_size) return 0;
v->data = p;
v->size += extr_size;
return 1;
}
#if 0
int expand(Vec *v) {
int *tmp = v->data;
v->data = (int *)malloc(sizeof(int) * v->size * 2);
v->size *= 2;
memcpy(v->data, tmp, v->length * sizeof(int));
free(tmp);
return 1;
}
#endif
int insert(Vec *v, int val, int ind) {
if (!v) return 0;
if (ind < 0 || ind > v->length) return 0;
if (v->length >= v->size) {
if (!expand(v)) return 0;
printf("success to expand! Vector size is %d\n", v->size);
}
for (int i = v->length; i > ind; i--) {
v->data[i] = v->data[i - 1];
}
v->data[ind] = val;
v->length++;
return 1;
}
int erase(Vec *v, int ind) {
if (!v) return 0;
if (ind < 0 || ind >= v->length) return 0;
for (int i = ind + 1; i < v->length; i++) {
v->data[i - 1] = v->data[i];
}
v->length--;
return 1;
}
void clear(Vec *v) {
if (!v) return ;
free(v->data);
free(v);
return ;
}
void output(Vec *v) {
if (!v) return;
printf("Vector : [");
for (int i = 0; i < v->length; i++) {
i && printf(" ");
printf("%d", v->data[i]);
}
printf("]\n");
}
int main() {
srand(time(0));
#define max_op 30
Vec *vec = init(max_op / 3);
for (int i = 0; i < max_op; i++) {
int val = rand() % 100;
int ind = rand() % (vec->length + 3) - 1;
int op = rand() % 10;
switch (op) {
case 0 ... 8: {
printf("insert %d at %d to Vector = %d\n", val, ind, insert(vec, val, ind));
} break;
case 9: {
printf("erase a iterm at %d from Vector = %d\n", ind, erase(vec, ind));
} break;
}
output(vec);
printf("\n");
}
clear(vec);
#undef max_op
return 0;
}