vector <double>在c ++代码中加倍错误</double>

时间:2014-07-10 18:43:24

标签: c++ random vector

我试图返回一个在加权随机分布上返回的向量中的值(即如果向量具有1,2,3,它将给出1/6的几率和1/2的概率2和3/6的几率3)。我得到编译时错误

Protein.cpp:809:54: error: cannot convert ‘__gnu_cxx::__normal_iterator<double*, std::vector<double> >’ to ‘double’ in assignment
Protein.cpp:814:24: error: could not convert ‘((Protein*)this)->Protein::fitness1.std::vector<_Tp, _Alloc>::operator[]<double, std::allocator<double> >((std::vector<double, std::allocator<double> >::size_type)index)’ from ‘double’ to ‘std::vector<double>’

当我编译代码并且尝试修复它时运气很少。如果有人可以看看这个功能并帮助我,我会非常感激。再次感谢你的时间!

功能

vector<double> Protein::Init_Seq_Recursive(State& s, int d)
{
    vector<float> sequence;
    double index;
    float initial;
    int i =0;
    for (i; i < k; i++)
    {
        s[d] = i;
        if (d == (L - 1))
        {
            int ind = Index(s);


            Ef[ind] = GetEf(s);
            Eb1[ind] = GetEb1(s);
            Eb2[ind] = GetEb2(s);
            double zf = exp(beta_f*Ef[ind]);
            double zb1 = exp(beta_b*Eb1[ind]);
            double zb2 = exp(beta_b*Eb2[ind]);


            fitness1[ind] = (1. + f_ub*zb1 + f_ub*f_uf*zf*zb1)/( 1. + zb1 + zf*zb1 );
            fitness2[ind] = (1. + f_ub*zb2 + f_ub*f_uf*zf*zb2)/( 1. + zb2 + zf*zb2 );



        }       
        else
            Init_Fitness_Recursive(s, d + 1);
    }
    if(i==k-1){
        vector<float> weights;
        float running_total = 0;


        for(int y = 0; y<pow(k,L); y++){
            running_total = running_total+fitness1[y];
            weights.push_back(running_total);


        }
        double rnd = (static_cast <double> (rand()) / static_cast <double> (RAND_MAX))*running_total;
        for(int y = 0; y<fitness1.size(); y++){
            if(rnd<weights[y]){
            index = find(fitness1.begin(), fitness1.end(), rnd);
            }       
        }

    }
    return(fitness1[index]);

}

2 个答案:

答案 0 :(得分:2)

std::find不会返回索引。它返回一个指向找到的元素的迭代器。要获取index,您需要计算begin迭代器与找到的迭代器之间的距离。像这样:

vector<double>::iterator found = find(fitness1.begin(), fitness1.end(), rnd);
index = distance(fitness1.begin(), found);

非常怀疑你会使用double作为容器的索引。

此外,您的return(fitness1[index]);正在尝试返回单个double,但您的返回类型为vector<double>

答案 1 :(得分:2)

index = find(fitness1.begin(), fitness1.end(), rnd);

find的返回值是迭代器。您需要取消引用它才能获得doubleindex的类型):

index = *find(fitness1.begin(), fitness1.end(), rnd);
//      ^

其次,您尝试从声明为返回double的函数返回vector<double>

return( fitness1[index] );
//      ^^^^^^^^^^^^^^^