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

来源:互联网 发布:php substr函数 中文 编辑:程序博客网 时间:2024/05/16 12:42

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

 

#include <stdio.h>#include <conio.h>#include <stdlib.h>//=============================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;i<this->size;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