文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Data Abstraction(Chapter 4 of Thinking in C++)

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

时间:2010-11-10  来源:Ray Z

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 }

 

 

相关阅读 更多 +
排行榜 更多 +
坦克冒险大师安卓版

坦克冒险大师安卓版

策略塔防 下载
自动防御

自动防御

策略塔防 下载
枪战大乱斗2

枪战大乱斗2

飞行射击 下载