牛骨文教育服务平台(让学习变的简单)
博文笔记

数组自动变长

创建时间:2017-12-23 投稿人: 浏览次数:153
#include <iostream>
#include<string.h>
using namespace std;
class Text
{
private:
    int size;
    int capablity;
    char* buffer;
    void resize();
public:
    Text()
    {
        size=0;
        capablity=4;
        buffer=new char[capablity];
    }
    Text(int capablity)
    {
        size=0;
        this->capablity=capablity;
        buffer=new char[capablity];
    }
    void push(int x);
    void show();
};

void Text::resize()
{

    capablity+=4;
    char* temp=new char [capablity];
    memcpy(temp,buffer,strlen(buffer));
    delete []buffer;
    buffer=temp;
}

void Text::push(int x)
{
   // size++;
    while(size==capablity)
    {
        resize();
    }

    buffer[size++]=x;
}

void Text::show()
{
    for( int i=0;i<size;i++)
        cout<<(int)buffer[i]<<" ";
    cout<<endl;
}

int main()
{
    Text text;
    for( int i=0;i<40;i++)
        text.push(i+1);
    text.show();
    return 0;
}

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。