lambda函数c ++ 11

Jas*_*erK -2 c++ audio fmod c++11

知道如何重写这个lambda函数pre c ++ 11吗?

    if (maxVol != 0)
       std::transform(&spec[0], &spec[sampleSize], &spec[0]
                     , [maxVol] (float dB) -> float {   return dB / maxVol; });
Run Code Online (Sandbox Code Playgroud)

代码来自http://katyscode.wordpress.com/2013/01/16/cutting-your-teeth-on-fmod-part-4-frequency-analysis-graphic-equalizer-beat-detection-and-bpm-估计

谢谢

Moo*_*uck 5

原始代码:

if (maxVol != 0)
       std::transform(&spec[0], &spec[sampleSize], &spec[0], [maxVol] (float dB) -> float {   return dB / maxVol; });
Run Code Online (Sandbox Code Playgroud)

LAMBDA:

[maxVol] (float dB) -> float {   return dB / maxVol; }
Run Code Online (Sandbox Code Playgroud)

替换lambda:

struct percent_of {
    //that lambda captures maxVol by copy when constructed
    percent_of(float maxVol) : maxVol(maxVol) {} 
    //the lambda takes a "float dB" and returns a float
    float operator()(float dB) const { return dB / maxVol; }
private:
    float maxVol;
};
Run Code Online (Sandbox Code Playgroud)

替换完整代码:

if (maxVol != 0)
       std::transform(&spec[0], &spec[sampleSize], &spec[0], percent_of(maxVol));
Run Code Online (Sandbox Code Playgroud)

但是,这个lambda非常简单,现在已经内置到标准库中.Pre-C++ 11具有完全相同的位boost.

if (maxVol != 0) {
    using std::placeholders::_1;
    auto percent_of = std::bind(std::divides<float>(), _1, maxVol);
    std::transform(&spec[0], &spec[sampleSize], &spec[0], percent_of);
}
Run Code Online (Sandbox Code Playgroud)