前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >袖珍C库

袖珍C库

作者头像
用户1154259
发布2018-01-17 15:01:32
5400
发布2018-01-17 15:01:32
举报
代码语言:javascript
复制
 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 }

执行结果:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2012-10-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档