CppLib.h1structStash
2{
3intsize;
4intquantity;
5intnext;
6unsignedcharstorage;
7voidinitialize(intsize);
8voidcleanup();
9intadd(constvoidelement);
10void*fetch(intindex);
11intcount();
12voidinflate(intincrease);
13};
CppLib.cpp1#include"CppLib.h"
2#include<iostream>
3#include<cassert>
4usingnamespacestd;
5
6constintincrement=100;
7
8voidStash::initialize(intsize)
9{
10this->size=size;
11quantity=0;
12storage=0;
13next=0;
14}
15
16intStash::add(constvoidelement)
17{
18if(next>=quantity)
19{
20inflate(increment);
21}
22
23intstartBytes=nextsize;
24unsignedchare=(unsignedchar)element;
25for(inti=0; i<size; i++)
26{
27storage[startBytes+i]=e[i];
28}
29next++;
30return(next-1);
31}
32
33voidStash::fetch(intindex)
34{
35assert(0<=index);
36if(index>=next)
37{
38return0;
39}
40
41return&(storage[indexsize]);
42}
43
44intStash::count()
45{
46returnnext;
47}
48
49voidStash::inflate(intincrease)
50{
51assert(increase>0);
52intnewQuantity=quantity+increase;
53intnewBytes=newQuantitysize;
54intoldBytes=quantitysize;
55unsignedchar*b=newunsignedchar[newBytes];
56for(inti=0; i<oldBytes; i++)
57{
58b[i]=storage[i];
59}
60delete []storage;
61storage=b;
62quantity=newQuantity;
63}
64
65voidStash::cleanup()
66{
67if(storage!=0)
68{
69cout<<"freeeing storage"<<endl;
70delete []storage;
71}
72}
CppLibTest.cpp1#include"CppLib.h"
2#include<fstream>
3#include<iostream>
4#include<string>
5usingnamespacestd;
6
7intmain()
8{
9Stash intStash;
10intStash.initialize(sizeof(int));
11for(inti=0; i<100; i++)
12{
13intStash.add(&i);
14}
15
16for(intj=0; j<intStash.count(); j++)
17{
18cout<<"intStash.fetch("<<j<<") ="
19<<(int)intStash.fetch(j)<<endl;
20}
21
22Stash stringStash;
23constintbufsize=80;
24stringStash.initialize(sizeof(char)bufsize);
25ifstreamin("CppLibTest.cpp");
26stringline;
27while(getline(in, line))
28{
29stringStash.add(line.c_str());
30}
31
32intk=0;
33charcp;
34while((cp=(char*)stringStash.fetch(k++))!=0)
35{
36cout<<"stringStash.fetch("<<k<<") ="
37<<cp<<endl;
38}
39
40intStash.cleanup();
41stringStash.cleanup();
42cin.get();
43}
原文链接: https://www.cnblogs.com/zhtf2014/archive/2010/11/10/1873278.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/17187
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!