如何在 turbo C++ 中增加类数组的大小?

How do I Increase the size of a Class array? in turbo c++

本文关键字:数组 增加 turbo C++      更新时间:2023-10-16

我写了这个类:

class Spacewalk {
private: 
char mission[50];
char date[50];
char astronaut[50];
char startingAt[50];
char endingAt[50];
public:
void list() {
// lists the values.
}
void addValue(miss, da, astro, start, end) {
// adds value to the private items.
}
};

我创建了一个此类数组,如下所示 -

Spacewalk list[1]; 

比方说,我已经用完了这个数组的空间,我将如何增加它的大小?

数组非常适合学习编码的概念,因此我比任何其他标准模板库(在学习代码时(都更认可它们。

注意:
使用vector是明智的,但是学校不教这个的原因是因为他们希望您了解诸如vectorstackqueue之类的事物背后的基本概念。 如果不了解汽车的各个部分,就无法制造汽车。

可悲的是,在调整数组大小时,除了创建一个新数组并传输元素之外,没有简单的方法。 执行此操作的最佳方法是保持数组动态。

请注意,我的示例适用于int(s(,因此您必须将其制作成模板或将其更改为所需的类。

#include <iostream>
#include <stdio.h>
using namespace std;

static const int INCREASE_BY = 10;
void resize(int * pArray, int & size);

int main() {
// your code goes here
int * pArray = new int[10];
pArray[1] = 1;
pArray[2] = 2;
int size = 10;
resize(pArray, size);
pArray[10] = 23;
pArray[11] = 101;
for (int i = 0; i < size; i++)
cout << pArray[i] << endl;
return 0;
}

void resize(int * pArray, int & size)
{
size += INCREASE_BY;
int * temp = (int *) realloc(pArray, size);
delete [] pArray;
pArray = temp;
}