用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c++代码库

stash的struct类型相关代码

2013-02-24 作者: 程序猿style举报

[c++]代码库

//stash.h文件
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
 
struct Stash
{
 
    int size;
    int quantity;
    int next;
    unsigned char* storage;
    void initialize(int Size);
    void cleanup();
    int add( void* element);
    void* fetch(int index);
    int count();
    void inflate(int increase);
};
//stash.cpp文件
#include "stash.h"
 
const int CREASE_SIZE = 100;
Stash::Stash(int Size)
{
    size = Size;
    quantity = 0;
    storage = 0;
    next = 0;
}
Stash::Stash(int Size,int InitQuant)
{
    size = Size;
    quantity = 0;
    next = 0;
    storage = 0;
    inflate(InitQuant);
}
void Stash::cleanup()
{
    if (storage)
    {
        cout<<"freeing storage"<<endl;
        free(storage);
    }
}
 
int Stash::add(void* element)
{
    if (next >= quantity)
    {
        inflate(CREASE_SIZE);
    }
    memcpy(&(storage[next*size]),element,size);
    next++;
    return next - 1;
}
 
void* Stash::fetch(int index)
{
    if ((index >= next) || index < 0)
    {
        return 0;
    }
    return &(storage[index*size]);
}
int Stash::count()
{
    return next;
}
 
void Stash::inflate(int increase)
{
    void* v = realloc(storage,(quantity+increase)*size);
    assert(v);
    storage = (unsigned char*)v;
    quantity += increase;
}
//stash的main()函数文件
#include "stash.h"
const int BUFSIZE = 80;
int main(void)
{
    Stash intStash;
    int i;
    intStash.initialize(sizeof(int));
    for (i=0; i<100; i++)
    {
        intStash.add(&i);
    }
    for (i=0; i<intStash.count(); i++)
    {
        cout<<*(int*)intStash.fetch(i)<<" ";
    }
    cout<<endl;
    intStash.cleanup();
     
    //Stash stringStash;
    //FILE* file;
    //char buf[BUFSIZE];
    //char* cp;
    //stringStash.initialize(sizeof(char)*BUFSIZE);
    //file = fopen("test.cpp","r");
    //assert(file);
    //while (fgets(buf,BUFSIZE,file))
    //{
    //  stringStash.add(buf);
    //}
    //fclose(file);
    //
    //i = 0;
    //while (((cp = (char*)stringStash.fetch(i++)) != 0))
    //{
    //  cout<<cp<<" ";
    //}
    //cout<<endl;
    //stringStash.cleanup();
    return 0;
}


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...