用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;}
相关文章推荐
- 1023. Have Fun with Numbers (20)
- Leetcode 14. Longest Common Prefix
- C++ 运算符重载
- C++ typedef用法详解
- Leetcode 13. Roman to Integer
- 课程设计__C++初步,C++对C的扩充
- Leetcode 12. Integer to Roman
- C++面试题汇集
- C++面试题汇集
- c++ Muitmaps
- 从c++到java的简单过渡
- c语言 翻译密码
- C++的Static函数
- 《More Effective C++》读书笔记-异常
- 程序源入坑之路5(c语言入门)
- c++ 实现字符串中替换字符串,也可去掉字符串中特定字符串
- C++错误集合
- C语言书籍推荐
- 山东省第三届ACM大学生程序设计竞赛-Pixel density(模拟)
- C++ 左值引用和右值引用(C++11特性)