2011-04-14 67 views
1

很抱歉,如果標題是不明確的,但現在我會解釋我的問題。我是C++新手。如何存儲未知數量的元素數組中的C++

我已經建立在C++的類。該類的實例是程序的輸入,它們必須存儲在數組中以執行計算。問題在於,必須由用戶定義的那個類的實例的數量對於單次運行是固定的,但可以隨着運行而變化。下面一個例子:

#include <<blablah>blahblah> 

int main() 
{ 
int number_of_instances = 3; 

MyClass first_instance(one_parameter_1, another_parameter_1); 
MyClass second_instance(one_parameter_2, another_parameter_2); 
MyClass third_instance(one_parameter_3, another_parameter_3); 

///////////////////

現在我已經來存儲所有三種陣列中的LIKE

MyClass array[number_of_instances] = {first_instance, second_instance, third_instance}; 

的問題是,我不知道前手有多少人是在用戶即將輸入

///////////////////

performCalculations(array); 
return 0; 
} 

非常感謝。

+0

使用鏈表? – Ross 2011-04-14 18:43:00

+1

...或數組和可變計數器。 – Ross 2011-04-14 18:44:04

+0

使用'std :: vector',本主題描述了幾種優雅的方式來填充你的矢量:[實現數組初始化](http://stackoverflow.com/questions/5395595/implementing-array-initializer) – Nawaz 2011-04-14 18:49:03

回答

6

典型的C++解決方案是使用一個vector

vector<MyClass> v; 
v.push_back(first_instance); //add an already instantiated object to the end of the vector 
v.push_back(second_instance); 
v.push_back(third_instance); 

您將不必擔心內存管理,你能夠訪問你這樣的載體將一個正常的數組:

v[0].classMember 

您也可以在一個循環中添加項目到矢量當矢量超出範圍,如果你在矢量直接存儲對象

for(int i = 0; i < 5; i++){ 
    v.push_back(MyClass(i, param2)); 
} 

而且所有的對象都將被破壞:如果需要的話,像這樣。

其中一個缺點直接在矢量存儲的對象的經過所述向量作爲參數的函數。這將是一個緩慢的操作,因爲矢量(及其所有對象)將不得不被複制。

+0

非常感謝你們。好吧,我理解這個概念,但現在的問題是,如果我不知道其中會有多少人。如果我不知道其中會有多少實例,我如何添加更多v.push_back實例(number_instance)。 – Altober 2011-04-14 18:50:58

+0

@Altober - 是的,你可以繼續調用push_back函數來添加更多元素 – DShook 2011-04-14 18:52:58

+0

@DShook非常感謝。對不起,可能我太可怕了,但我明白我可以編寫一個for循環來繼續調用push_back,但是如何在for循環的不同迭代中將實例名稱更改爲first_instance,second_instance,third_instance等。 – Altober 2011-04-14 18:57:27

0

如果你不知道數組有多少元素包含,我會用一個std::vector而不是一個普通數組作爲載體將增長以容納更多的元素。

0

你需要的是從標準模板庫中的Vector類,它像一個數組,但它會重新本身的大小,如果你填補它的內部分配。如果您不需要隨機訪問它(即使用[] opperator),您可能需要使用List類。如果你使用List,你將需要創建一個枚舉器來遍歷它。

0

使用std::vector<MyClass>,vector模板可以在<vector>標題中找到。你必須學會​​一點點的代碼好,編碼使用任何網絡的可用的C++常見問題

1

你應該在這種情況下,使用std :: vector而不是內置陣列之前。

#include <vector> 
... 
std::vector<MyClass> v = {first_instance, second_instance, third_instance}; 
... 
v.push_back(fourth_instance); 
+0

這不會在C++ 03中起作用。 – Nawaz 2011-04-14 19:00:44

2

如果您知道實例數您在閱讀它們,那麼你可以分配使用new[]堆陣列之前。 (完成後別忘了delete[])。注意這需要對象具有默認的構造函數。

+0

對不起尼爾你是什麼意思閱讀他們?感謝你的回答。 – Altober 2011-04-14 19:02:14

+0

你說他們是程序的輸入,所以我假設他們需要以某種方式閱讀,並且你可能事先知道你需要輸入多少。 – Neil 2011-04-14 19:05:54

相關問題