带有C风格的 CLib库

#include"CLib.h"
#include<iostream>
#include<string>
#include<cassert>
#include<fstream>
using namespace std;
int main() {
    CStash intStash, stringStash;
    int i;
    char* cp;
    ifstream in;
    string line;
    const int bufsize = 80;
    initialize(&intStash, sizeof(int));
    for ( i = 0; i < 100; i++)
    {
        add(&intStash, &i);
    }
    for (i = 0; i < count(&intStash); i++)
    {
        cout << "fetch(&intStash," << i << ") = "
            << *(int*)fetch(&intStash, i)
            << endl;
    }
    cleanup(&intStash);
    system("pause");
    
}
#ifndef CLIB_H
#define CLIB_H

typedef struct CStashTag {
    int size;
    int quantity;
    int next;
    unsigned char* storage;
}CStash;

void initialize(CStash* s, int size);
void cleanup(CStash *s);
int add(CStash *s, const void* element);
void* fetch(CStash*s, int index); //
int count(CStash* s);
void inflate(CStash* s, int increate);//增加

#endif // !CLIB_H
#include "CLib.h"
#include<iostream>
#include<cassert>
using namespace std;
const int increment = 100;

void initialize(CStash * s, int size)
{
    s->size = size;
    s->quantity = 0;
    s->storage = 0;
    s->next = 0;
}

void cleanup(CStash * s)
{
    if (s->storage != 0)
        cout << "free" << endl;
    delete[] s->storage;
}

int add(CStash * s, const void * element)
{
    if(s->next>=s->quantity)
        inflate(s,increment );
    int startBytes = s->next* s->size;
    unsigned char *e = (unsigned char *)element;
    for (int i = 0; i < s->size; i++)
        s->storage[startBytes + i] = e[i];
    s->next++;
    
    return (s->next - 1);
}

void * fetch(CStash * s, int index)
{
    assert(0 <= index);
    if (index >= s->next)
        return 0;
    return &(s->storage[index*s->size]);
}

int count(CStash * s)
{
    return s->next;
}

void inflate(CStash * s, int increate)
{
    assert(increate > 0);
    int newQuantity = s->quantity + increment;
    int newBytes = newQuantity * s->size;
    int oldBytes = s->quantity*s->size;
    unsigned char *b = new unsigned char[newBytes];
    for (int i = 0; i < oldBytes; i++)
    {
        b[i] = s->storage[i];
    }
    delete[](s->storage);
    s->storage = b;
    s->quantity = newQuantity;

}

 

class Stash {
    struct Link {
        void *data;
        Link* next;
        void init(void* dat, Link* nxt);
    }*head;
public:
    void init();
    void push(void *dat, Link* nxt);
    void *peek();
    void* pop();
    void cleanup();
};

 

posted @ 2018-12-04 08:30  Lumi_Imp  阅读(816)  评论(0编辑  收藏  举报