2017-08-01 39 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; 

}