您的位置:首页 > 编程语言 > C语言/C++

用C++写Stash

2016-04-30 20:44 337 查看
#ifndef CPPLIB_H_#define CPPLIB_H_class Stash{<span style="white-space:pre">	</span>int size;<span style="white-space:pre">	</span>int quantity;<span style="white-space:pre">	</span>int next;<span style="white-space:pre">	</span>unsigned char* storage;public:<span style="white-space:pre">	</span>void initialize(int size);<span style="white-space:pre">	</span>int add(const void* element);<span style="white-space:pre">	</span>void inflate(int increase);<span style="white-space:pre">	</span>int count();  // 计算Stash里的数据有多少个,<span style="white-space:pre">	</span>void* fetch(int index);  //取指针里的数,<span style="white-space:pre">	</span>void cleanup();  // 清除,把分配的内存释放,};#endif
#include "Cpplib.h"#include <cstdlib>#include <cassert> // 这个是断言的头文件,const int increment = 100;void Stash::initialize(int sz){size = sz;quantity = 0;next = 0;storage = 0;}int Stash::add(const void* element){if (next >= quantity)inflate(increment);int startBytes = next *size;unsigned char *e = (unsigned char*)element;for (int i = 0; i < size; i++)storage[startBytes + i] = e[i];next++;return (next - 1); // 返回的是位置,}void Stash::inflate(int increase){assert(increase > 0);int newQuantity = quantity + increase;int newBytes = newQuantity * size;int oldBytes = quantity * size;unsigned char* b = new unsigned char[newBytes];for (int i = 0; i < oldBytes; i++)b[i] = storage[i];delete storage;storage = b;quantity = newQuantity;}int Stash::count(){return next;}void* Stash::fetch(int index){assert(0 <= index);if (index >= next)  // 如果这个索引超出最大的索引就返回0,就结束了,return 0;return &(storage[index * size]);  //返回的是一个地址,}void Stash::cleanup(){if (storage != 0){delete[] storage;}}
#include <iostream>#include "Cpplib.h"#include <fstream>  // 文件输入流,#include <cassert>#include <string>using namespace std;int main(){Stash intStash, stringStash;const int bufsize = 80;intStash.initialize(sizeof(int));for (int i = 0; i < 150; i++)intStash.add(&i);for (int i = 0; i < intStash.count(); i++)cout << *(int*)intStash.fetch(i) << endl;  // 利用指针将里边的数取出来,fetch是一个万能指针将其转化成int类型的,stringStash.initialize(bufsize * sizeof(char));ifstream in;in.open("main.cpp");  // 这个是利用文件输入流去打开文件,assert(in);string line;while (getline(in, line))stringStash.add(line.c_str());  // add 的第二个参数是c语言的指针,所以用c_str,int k = 0;char* cp;  //字符指针,while ((cp = (char*)stringStash.fetch(k++)) != 0)cout << cp << endl;intStash.cleanup();stringStash.cleanup();system("pause");return 0;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: