C++ 在c+中初始化自定义类的向量+;

C++ 在c+中初始化自定义类的向量+;,c++,constructor,vector,initialization,C++,Constructor,Vector,Initialization,嘿,基本上,我试图存储一个“解决方案”,并创建一个向量。我遇到的问题是初始化。这是我的课供参考 class Solution { private: // boost::thread m_Thread; int itt_found; int dim; pfn_fitness f; double value; std::vector<double> x; public: Sol

嘿,基本上,我试图存储一个“解决方案”,并创建一个向量。我遇到的问题是初始化。这是我的课供参考

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*/
}

我已经在类似这样的任务中使用了Boost。您可能会发现它很有用……

我作为注释给出的示例使用复制构造函数创建新对象。 您可以执行以下操作:

// override copy constructor
Solution(const Solution &solution) {
... copy from another solution
}
但是要小心,因为如果在复制构造函数中引入随机生成,就不再有精确的对象复制/构造,即
solutiony y=x;y!=x


在我看来,您最好的解决方案是您已经拥有的

您可以初始化为如下值:
向量(大小,解决方案(21,0))非常好的参考,谢谢这正是我想要的。@aaa,应该是一个答案…实际上。。。测试后,当我这样做时,所有的x在每个解决方案中都得到相同的值(即Parents[I].GetX()[j]=Parents[I+1].GetX()[j],所以这并不完全是我想要的两点:x的第一个元素从未初始化(可能是设计的?)。您的副本分配似乎有些浪费,并且可能不正确,您可能希望将解决方案作为引用传递并返回*此作为引用。这样,您现在可以创建新的解决方案,然后返回另一个新的解决方案。如果这是设计的,请忽略。我将对此进行研究,因为我已经在使用boost threading l该项目的图书馆
// override copy constructor
Solution(const Solution &solution) {
... copy from another solution
}