2010-05-22 79 views
2

嘿基本上我試圖存儲一個「解決方案」,並創建這些向量。我遇到的問題是初始化。我的繼承人蔘考在C++中初始化自定義類的向量

class Solution 
{ 
private: 
     // boost::thread m_Thread; 
     int itt_found; 
     int dim; 
     pfn_fitness f; 
     double value; 
     std::vector<double> x; 
public: 

     Solution(size_t size, int funcNo) : itt_found(0), x(size, 0.0), value(0.0), dim(30), f(Eval_Functions[funcNo]) 
     { 
      for (int i = 1; i < (int) size; i++) { 
       x[i] = ((double)rand()/((double)RAND_MAX))*maxs[funcNo]; 
      } 
     } 

     Solution() : itt_found(0), x(31, 0.0), value(0.0), dim(30), f(Eval_Functions[1]) 
     { 
      for (int i = 1; i < 31; i++) { 
       x[i] = ((double)rand()/((double)RAND_MAX))*maxs[1]; 
      } 
     } 
     Solution operator= (Solution S) 
     { 
      x = S.GetX(); 
      itt_found = S.GetIttFound(); 
      dim = S.GetDim(); 
      f = S.GetFunc(); 
      value = S.GetValue(); 
      return *this; 
     } 
     void start() 
     { 
      value = f (dim, x); 
     } 
     /* plus additional getter/setter methods*/ 
} 

Solution S(30, 1)Solution(2, 5)工作和階級initalizes一切,但我需要這些解決方案的對象X。 std::vector<Solution> Parents(X)將使用默認構造函數創建X解決方案,並且我想使用(int,int)構造函數進行構造。有沒有簡單的方法可以做到這一點?或者我將不得不這樣做:

size_t numparents = 10; 
vector<Solution> Parents; 
    Parents.reserve(numparents); 
    for (int i = 0; i<(int)numparents; i++) { 
     Solution S(31, 0); 
     Parents.push_back(S); 
    } 
+0

你可以初始化爲像這樣的值:'vector(size,Solution(21,0));' 供參考http://www.cplusplus.com/reference/stl/矢量/矢量/ – Anycorn 2010-05-22 01:46:37

+0

美好,謝謝那正是我想要的。 – Flamewires 2010-05-22 01:48:58

+0

@aaa,應該是一個答案... – Kiril 2010-05-22 02:11:45

回答

1

我給出的作爲註釋的示例使用了複製構造函數來創建新對象。 你可以做到以下幾點:

// override copy constructor 
Solution(const Solution &solution) { 
... copy from another solution 
} 

但是要小心,因爲你不再將有確切的對象複製/如果您在拷貝構造函數引入隨機生成構造,即Solution y = x; y != x

你最好的解決辦法是像你已經在我的意見

+0

中使用了boost線程庫,謝謝,我可能會保持原樣。 – Flamewires 2010-05-22 05:47:26

1

我已經使用Boost assignment library這樣的任務。您可能會發現它很有用。...

+0

我會研究這我已經在這個程序 – Flamewires 2010-05-22 05:47:51