c语言实现容器,C语言实现类似于C++的Vector容器

C语言实现类似于C++的Vector容器

#include #include #include //=============================Starting to define my Array class=========================

//-----------------------------Declaration segment-------------------------

typedef int DataType;

typedef struct array{

DataType *Data;

int size,max_size;

void (*Input)(DataType , struct array *);

void (*Constructor)(struct array *);

void (*Destructor)(struct array *);

}Array;

void Init(Array *this);

void _constructor(Array *this);

void _denstructor(Array *this);

void _input(DataType data, Array *this);

//------------------------------Implemen segment---------------------------

void _input(DataType data, Array *this)

{

int i;

DataType *ptr;

if(this->size >= this->max_size)

{

this->max_size +=10;

ptr=(DataType *)malloc(this->max_size*sizeof(DataType));

for(i=0;isize;i++)

ptr[i]=this->Data[i];

free(this->Data);

this->Data=ptr;

}

this->Data[this->size]=data;

++(this->size);

}

void _constructor(Array *this)

{

this->size=0;

this->max_size=10;

this->Data=(DataType *)malloc(this->max_size*sizeof(DataType));

}

void _denstructor(Array *this)

{

free(this->Data);

}

void Init(Array *this)

{

this->Input =_input;

this->Constructor =_constructor;

this->Destructor =_denstructor;

this->Constructor(this);

}

//===================================definition end===============================

// 使用示例

int main()

{

Array MyArray;

Init(&MyArray); //使用对象前必须初始化,间接调用构造函数

MyArray.Input(1,&MyArray);

MyArray.Input(2,&MyArray);

printf("The elements of MyArray : %d,\t%d",MyArray.Data[0],MyArray.Data[1]);

getch();

MyArray.Destructor(&MyArray); //使用对象后必须显式调用析构函数

return 0;

}

参考:

http://cache.baidu.com/c?m=9d78d513d99256ae28fae27f1a61a3716f5797153ac0d06468a4965fe3174c31377190cf3365505adc9f3a2143b8482ff7ed6622761420c0cb99d916cabbe57478ce3a722a5cd11244c419d9c8422fca24914de9d91af0ba863184aea589990b0d&p=8f769a46dc934eae5ef7d52549059c&user=baidu&fm=sc&query=C%D3%EF%D1%D4+%B7%BA%BB%AF&qid=e17c2c360759565b&p1=1

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值