c++ - vector <double> 将 c++ 代码中的错误加倍

标签 c++ random vector

我正在尝试返回一个 vector 中的值,该 vector 按加权随机分布返回(即,如果 vector 有 1,2,3,它将给出 1/6 的机会和 2/6 的机会2 和 3/6 的机会)。我收到

的编译时错误
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]);

}

最佳答案

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> .

关于c++ - vector <double> 将 c++ 代码中的错误加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24684020/

相关文章:

bash - 如何在 bash 中获得 0 到 999999999 之间的随机数 (/dev/random)?

javascript - 单击时生成相同的随机数

vector - 在 clojure 中,通过内核对向量进行卷积的有效方法是什么?

c++ - 使用 localtime_s 获取当前日期

c++ - Cocos2dx v.3.0 人像模式

javascript - 如何获取 HTML 表单中的 JS 函数结果?

S 表达式的列表,(文字)数据的向量?

c++ - 使用cmake生成compile_commands.json

c++ - 访问作为非类型模板参数传递的std数组元素会在msvc上给出非编译时常量值

java - Java中初始化一个Vector对象,总是不对