//stash.h文件 |
#include <iostream> |
#include <string> |
#include <assert.h> |
using namespace std; |
struct Stash |
{ |
int size; |
int quantity; |
int next; |
unsigned char * storage; |
void initialize( int Size); |
void cleanup(); |
int add( void * element); |
void * fetch( int index); |
int count(); |
void inflate( int increase); |
}; |
//stash.cpp文件 |
#include "stash.h" |
const int CREASE_SIZE = 100; |
Stash::Stash( int Size) |
{ |
size = Size; |
quantity = 0; |
storage = 0; |
next = 0; |
} |
Stash::Stash( int Size, int InitQuant) |
{ |
size = Size; |
quantity = 0; |
next = 0; |
storage = 0; |
inflate(InitQuant); |
} |
void Stash::cleanup() |
{ |
if (storage) |
{ |
cout<< "freeing storage" <<endl; |
free (storage); |
} |
} |
int Stash::add( void * element) |
{ |
if (next >= quantity) |
{ |
inflate(CREASE_SIZE); |
} |
memcpy (&(storage[next*size]),element,size); |
next++; |
return next - 1; |
} |
void * Stash::fetch( int index) |
{ |
if ((index >= next) || index < 0) |
{ |
return 0; |
} |
return &(storage[index*size]); |
} |
int Stash::count() |
{ |
return next; |
} |
void Stash::inflate( int increase) |
{ |
void * v = realloc (storage,(quantity+increase)*size); |
assert (v); |
storage = (unsigned char *)v; |
quantity += increase; |
} |
//stash的main()函数文件 |
#include "stash.h" |
const int BUFSIZE = 80; |
int main( void ) |
{ |
Stash intStash; |
int i; |
intStash.initialize( sizeof ( int )); |
for (i=0; i<100; i++) |
{ |
intStash.add(&i); |
} |
for (i=0; i<intStash.count(); i++) |
{ |
cout<<*( int *)intStash.fetch(i)<< " " ; |
} |
cout<<endl; |
intStash.cleanup(); |
|
//Stash stringStash; |
//FILE* file; |
//char buf[BUFSIZE]; |
//char* cp; |
//stringStash.initialize(sizeof(char)*BUFSIZE); |
//file = fopen("test.cpp","r"); |
//assert(file); |
//while (fgets(buf,BUFSIZE,file)) |
//{ |
// stringStash.add(buf); |
//} |
//fclose(file); |
// |
//i = 0; |
//while (((cp = (char*)stringStash.fetch(i++)) != 0)) |
//{ |
// cout<<cp<<" "; |
//} |
//cout<<endl; |
//stringStash.cleanup(); |
return 0; |
} |