袖珍C库

 1 #include "StdAfx.h"
 2 #include <iostream>
 3 #include <fstream>
 4 #include <cassert>
 5 #include <string>
 6 
 7 using namespace std;
 8 
 9 const int increment = 100;
10 
11 typedef struct CStashTag{
12 int size;
13 int quantity;
14 int next;
15 unsigned char* storage;
16 }CStash;
17 
18 void initialize(CStash* s,int size);
19 void cleanup(CStash* s);
20 int add(CStash* s,const void* element);
21 void* fetch(CStash* s,int index);
22 int count(CStash* s);
23 void inflate(CStash* s,int increase);
24 
25 void initialize(CStash* s,int sz){
26     s->size = sz;
27     s->quantity = 0;
28     s->storage = 0;
29     s->next = 0;
30 }
31 
32 int add(CStash* s,const void* element){
33     if(s->next >= s->quantity)
34         inflate(s,increment);
35     int startBytes = s->next * s->size;
36     unsigned char* e=(unsigned char*)element;
37     for(int i=0;i<s->size;i++)
38         s->storage[startBytes + i] = e[i];
39     s->next++;
40     return(s->next -1);
41 }
42 
43 void* fetch(CStash* s,int index){
44     assert(0 <= index);
45     if(index >= s->next)
46         return 0;
47     return &(s->storage[index * s->size]);
48 }
49 
50 int count(CStash* s){
51     return s->next;
52 }
53 
54 void inflate(CStash* s,int increase){
55     assert(increase > 0);
56     int newQuantity = s->quantity + increase;
57     int newBytes = newQuantity * s->size;
58     int oldBytes = s->quantity*s->size;
59     unsigned char* b = new unsigned char[newBytes];
60     for(int i=0;i<oldBytes;i++)
61         b[i] = s->storage[i];
62     delete [](s->storage);
63     s->storage = b;
64     s->quantity = newQuantity;
65 }
66 
67 void cleanup(CStash* s){
68     if(s->storage != 0)
69     {
70         cout<<"freeing storage"<<endl;
71         delete []s->storage;
72     }
73 }
74 
75 int main()
76 {
77     CStash intStash,stringStash;
78     int i;
79     char* cp;
80     ifstream in;
81     string line;
82     const int bufsize = 80;
83     initialize(&intStash,sizeof(int));
84     for(i =0;i<100;i++)
85         add(&intStash,&i);
86     for(i=0;i<count(&intStash);i++)
87         cout<<"fetch(&intStash,"<<i<<")"<<*(int*)fetch(&intStash,i)<<endl;
88     initialize(&stringStash,sizeof(char)*bufsize);
89     in.open("stdafx.cpp");
90     assert(in);
91     while(getline(in,line))
92         add(&stringStash,line.c_str());
93     i=0;
94     while((cp=(char*)fetch(&stringStash,i++))!=0)
95         cout<<"fetch(&stringStash,"<<i<<")"<<cp<<endl;
96     cleanup(&intStash);
97     cleanup(&stringStash);
98     return 0;
99 }

执行结果:

posted @ 2012-10-10 19:46  xingoo  阅读(266)  评论(0编辑  收藏  举报