顺序表详解

文章详细描述了一个C++程序,使用自定义vector结构体实现动态内存管理,包括初始化、插入元素、删除元素以及输出向量内容。程序通过随机操作展示了向量的动态扩展和元素操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码实现:
#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值