2010-05-22 84 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