2017-08-01 57 views
-6

我写了这个类:如何增加Class数组的大小?在Turbo C++

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]; 

比方说,我用了这个阵列的空间,怎么样我会增加这个大小吗?

+4

使用'的std ::矢量 X;'代替'T X [N];',然后就可以'.resize'或'.push_back'。 –

+3

你可以使用'std :: vector '。也许'std :: string'而不是char数组? –

+0

你是指那个吗? https://stackoverflow.com/questions/12032222/how-to-dynamically-increase-the-array-size – pakkk

回答

1

数组非常适合学习编码的概念,因此我赞同它们比任何其他标准模板库(当涉及到学习代码时)更赞同它们。

注:
这是明智的使用vector然而,因为他们希望你能理解事物背后的基本概念,如vectorstack,或queue学校的理由不教这个。如果不理解其中的部分,你就无法创造汽车。

不幸的是,当涉及到调整数组大小时,除了创建一个新的数组和传输元素之外,没有简单的方法。最好的方法是保持阵列动态。

请注意我的示例是针对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; 

}