您的位置:首页 > 其它

】编写void put(int n)函数时,注意考虑数组满的情况

2017-01-19 09:51 751 查看
#include <iostream>

using namespace std;

class ListArray{

private:
int size;
int elem;
int *p;

public:
ListArray (int s = 100);
void put (int n);
void print ();
~ListArray();

};

ListArray::ListArray (int s)

{
size = s;
elem = 0;
p = new int[s];

}

void ListArray::put (int n)

{
int *pn;
int i;
if (elem == size)
{
size++;
pn = new int [size];
for (i = 0; i < elem; i++)
{
pn[i] = p[i];
}
pn[elem++] = n;
delete[] p;
p = pn;
}
else
{
p[elem++] = n;
}

}

void ListArray::print ()

{
int j;
cout << "所有元素:";
for (j = 0; j < elem; j++)
{
cout << p[j] << "  ";
}

cout << endl;
cout << "size = " << size << endl;

}

ListArray::~ListArray()

{
delete [] p;

}

int main ()

{
int b;
ListArray test (2);
while (1)
{
cout << "输入n:";
cin >> b;
test.put (b);
test.print();
}
/*ListArray test (2);
test.put(1);
test.put(2);
test.print();
test.put(3);
test.print();
test.put(5);
test.print();*/
return 0;
}

4.设定义一个类:

   class ListArray

{

   private:

     int size;   //整型数组的大小,表示可放元素的个数

     int elem;  //整型数组当前的元素个数,初始应为0,当elem等于size时,数组满

     int *p;    //指向整型数组,动态分配内存空间

   public:

     ListArray(int s=100); //用s初始化整型数组的大小

    void put(int n); //将n加入整型数组,elem自增1

    void print(); //输出整型数组所有元素

    ~ListArray();

  };

请完成该类成员函数的定义和测试程序的设计。

【提示】编写void put(int n)函数时,注意考虑数组满的情况。如果数组已满,则没有空间存储n,此时需动态申请新的内存空间,其大小应比原数组大小大1,并将原数组元素备份到新数组,新数组的最后一个元素存放n,当然不要忘记释放为原数组动态分配的内存空间。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐