#include<iostream>
#include<cassert>
using namespace std;
const int increment = 100;
//定义vector结构体
typedef struct CstashTag
{
unsigned char* strorage;
int size;
int quantity;
int next;
}Cstash;
//初始化函数
void Initialies(Cstash* s,int sz)
{
s->next = 0;
s->quantity = 0;
s->size = sz;
s->strorage = 0;
}
//首先开辟内存空间
void Inflate(Cstash* s,int increase)
{
if(increase <= 0)
{
cout<<"开辟空间无效";
return;
}
int newQuantity = s->quantity + increase;
int newBytes = newQuantity * s->size;
int oldBytes = s->quantity * s->size;
unsigned char* b = new unsigned char[newBytes];
for(int i = 0;i < oldBytes;i++)
b[i] = s->strorage[i];
delete [] (s->strorage);
s->strorage = b;
s->quantity = newQuantity;
}
//增加元素
int Add(Cstash* s,void * element)
{
if(s->next >= s->quantity)
Inflate(s,increment);
int stratBytes = s->next * s->size;
unsigned char* e = (unsigned char*)element;
for(int i = 0;i < s->size;i++)
s->strorage[stratBytes + i] = e[i];
s->next++;
return 1;
}
//获取元素 注意:这里是函数指针所返回地址
void* Fech(Cstash* s,int index)
{
if(index >= s->next)//千万注意这里的比较
return 0;
return &(s->strorage[index * s->size]);
}
//大小
int Count(Cstash* s)
{
return s->next;
}
//清除
void Clear(Cstash* s)
{
if(s->strorage != 0)
{
delete [] (s->strorage);
s->strorage = NULL;
}
}
int main()
{
Cstash pTest;
Initialies(&pTest,sizeof(int));
for(int i = 0;i < 100;i++)
{
Add(&pTest,&i);//插入元素
}
for(int i = 0;i < Count(&pTest);i++)
cout<<*(int*)(Fech(&pTest,i))<<endl;//输出元素
system("pause");
return 0;
}
手动实现类似容器---c++编程思想
最新推荐文章于 2024-08-05 15:04:38 发布