Ray's playground

 

Data Abstraction(Chapter 4 of Thinking in C++)

CppLib.h
 1 struct Stash
 2 {
 3     int size;
 4     int quantity;
 5     int next;
 6     unsigned char* storage;
 7     void initialize(int size);
 8     void cleanup();
 9     int add(const void* element);
10     void* fetch(int index);
11     int count();
12     void inflate(int increase);
13 };

 

CppLib.cpp
 1 #include "CppLib.h"
 2 #include <iostream>
 3 #include <cassert>
 4 using namespace std;
 5 
 6 const int increment = 100;
 7 
 8 void Stash::initialize(int size)
 9 {
10     this->size = size;
11     quantity = 0;
12     storage = 0;
13     next = 0;
14 }
15 
16 int Stash::add(const void* element)
17 {
18     if(next >= quantity)
19     {
20         inflate(increment);
21     }
22 
23     int startBytes = next * size;
24     unsigned char* e = (unsigned char*)element;
25     for(int i=0; i<size; i++)
26     {
27         storage[startBytes+i] = e[i];
28     }
29     next++;
30     return (next-1);
31 }
32 
33 void* Stash::fetch(int index)
34 {
35     assert(0 <= index);
36     if(index >= next)
37     {
38         return 0;
39     }
40 
41     return &(storage[index * size]);
42 }
43 
44 int Stash::count()
45 {
46     return next;
47 }
48 
49 void Stash::inflate(int increase)
50 {
51     assert(increase > 0);
52     int newQuantity = quantity + increase;
53     int newBytes = newQuantity * size;
54     int oldBytes = quantity * size;
55     unsigned char* b = new unsigned char[newBytes];
56     for(int i=0; i<oldBytes; i++)
57     {
58         b[i] = storage[i];
59     }
60     delete []storage;
61     storage = b;
62     quantity = newQuantity;
63 }
64 
65 void Stash::cleanup()
66 {
67     if(storage != 0)
68     {
69         cout << "freeeing storage" << endl;
70         delete []storage;
71     }
72 }

 

 

CppLibTest.cpp
 1 #include "CppLib.h"
 2 #include <fstream>
 3 #include <iostream>
 4 #include <string>
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     Stash intStash;
10     intStash.initialize(sizeof(int));
11     for(int i=0; i<100; i++)
12     {
13         intStash.add(&i);
14     }
15 
16     for(int j=0; j<intStash.count(); j++)
17     {
18         cout << "intStash.fetch(" << j << ") = "
19             << *(int*)intStash.fetch(j) << endl;
20     }
21 
22     Stash stringStash;
23     const int bufsize = 80;
24     stringStash.initialize(sizeof(char* bufsize);
25     ifstream in("CppLibTest.cpp");
26     string line;
27     while(getline(in, line))
28     {
29         stringStash.add(line.c_str());
30     }
31 
32     int k=0;
33     char* cp;
34     while((cp = (char*)stringStash.fetch(k++)) != 0)
35     {
36         cout << "stringStash.fetch(" << k << ") = "
37             << cp << endl;
38     }
39 
40     intStash.cleanup();
41     stringStash.cleanup();
42     cin.get();
43 }

 

 

posted on 2010-11-10 09:18  Ray Z  阅读(222)  评论(0编辑  收藏  举报

导航