
代码实现:
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include<iostream>
using namespace std;
#define MAX_OP 50
typedef struct vector
{
int capacity;
int size;
int* data;
}vector;
vector* getNewVector(int n) {
vector* v = (vector*)malloc(sizeof(vector));
v->size = 0;
v->capacity = n;
v->data = (int*)malloc(sizeof(int) * v->capacity);
return v;
}
int expand(vector* v) {
if (!v) return 0;
printf("Expand v from %d to %d\n", v->capacity, 2 * v->capacity);
int* p = (int*)realloc(v->data, v->capacity * sizeof(int) * 2);
if (!p) return 0;
v->data = p;
v->capacity *= 2;
return 1;
}
int insert(vector* v, int pos, int val) {
if (pos<0 || pos>v->size) return 0;
if (v->size == v->capacity && !expand(v)) return 0;
for (int i = v->size - 1; i >= pos; i--) {
v->data[i + 1] = v->data[i];
}
v->data[pos] = val;
v->size += 1;
return 1;
}
int erase(vector* v, int pos) {
if (pos < 0 || pos >= v->size) return 0;
if (v->size == 0) return 0;
for (int i = pos; i < v->size-1; i++) {
v->data[i] = v->data[i + 1];
}
v->size -= 1;
return 1;
}
void clear(vector* v) {
if (!v) return;
free(v->data);
free(v);
}
void output_vector(vector* v) {
int len = 0;
for (int i = 0; i < v->size; i++) {
len += printf("%-3d", i);
}
printf("\n");
for (int i = 0; i < len; i++) printf("-");
printf("\n");
for (int i = 0; i < v->size; i++) {
printf("%-3d", v->data[i]);
}
printf("\n\n\n");
return;
}
int main()
{
srand(time(0));
vector* v = getNewVector(2);
for (int i = 0; i < MAX_OP ; i++) {
int op = rand() % 4, pos, val, ret;
switch (op) {
case 0:
case 1:
case 2:
pos = rand() % (v->size + 2);
val = rand() % 100;
ret = insert(v, pos, val);
printf("insert %d at %d to vector = %d\n",
val, pos, ret);
break;
case 3:
pos = rand() % (v->size + 2);
ret = erase(v, pos);
printf("erase item at %d in vector = %d\n",
pos, ret);
break;
}
output_vector(v);
}
clear(v);
return 0;
}