How can I access local variables from inside a C++11 anonymous function?

后端 未结 3 1131
离开以前
离开以前 2020-12-24 06:29

I\'m doing a simple normalization on a vector (weights), trying to make use of STL algorithms to make the code as clean as possible (I realize this is pretty trivial with fo

3条回答
  •  时光说笑
    2020-12-24 06:44

    You need to add tot to the "capture list":

    float tot = std::accumulate(weights.begin(), weights.end(), 0);
    std::transform(weights.begin(), weights.end(), [tot](float x)->float{return(x/tot);});
    

    Alternatively you can use a capture-default to capture tot implicitly:

    float tot = std::accumulate(weights.begin(), weights.end(), 0);
    std::transform(weights.begin(), weights.end(), [=](float x)->float{return(x/tot);});
    

提交回复
热议问题