概述
这个数组可以向里面插入任何类型,包括自定义类型, 程序只是实现了基本功能,还有待完善,
首先初始化,然后就可以插入数据了, 当储存单元不足的时候就自动增加储存单元
由于总的风格是c, 所以看着很是别扭, 有空了把全部改成c++风格的;
说有空就有空了,改成了c++风格了, 至于新的功能感觉有困难, 主要要是自定义类型的查找问题,如果查找问题解决了就一切搞定,c++版的新增加了查找功能,但是感觉没什么用处, 我觉得应该像key-> value那样就好了,如果哪天想到怎么做了再补上
下面是全部代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <cassert>
using namespace std;
const int inCrement = 100; //每次增加的内存大小
typedef struct CStashTag
{
int size; // 单个储存单元的大小
int quantity; //储存单元的个数
int next; //指向storage数组最后的一个元素
unsigned char * storage; // 储存数据的数组,别误以为只能存char型额
}CStash;
typedef struct TestTag //向CStashTag里面插入的数据类型
{
int i;
char c;
double d;
TestTag(int i, char c, double d):i(i), c(c), d(d){}
}Test;
#define ElementType Test //向CStashTag里面插入的数据类型
const int Size = sizeof(ElementType); //单元大小
void ininialize(CStash *s, int size);
int add(CStash *s, const void *element);
void* fetch(CStash *s, int index);
void inflate(CStash *s, int inCrease);
void cleanup(CStash *s);
void initialize(CStash *s, int size)
{
s->size = size;
s->next = 0;
s->quantity = 0;
s->storage = 0;
}
int add(CStash *s, const void *element) //添加元素
{
if(s->next >= s->quantity) //内存不足就分配内存
inflate(s, inCrement);
int startBytes = s->next * s->size;
unsigned char *e = (unsigned char *) element;
for(int i = 0; i < s->size; i++) //将数据写到数组末尾
s->storage[startBytes + i] = e[i];
s->next++;
return s->next - 1;
}
void* fetch(CStash *s, int index) //返回数组下标为index的指针
{
assert(0 <= i
最后
以上就是美好毛豆为你收集整理的c/c++实现的一个动态分配内存的结构体数组(类似vector)的全部内容,希望文章能够帮你解决c/c++实现的一个动态分配内存的结构体数组(类似vector)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复