任何想法如何在c++ 11之前重写此lambda函数?
if (maxVol != 0)
std::transform(&spec[0], &spec[sampleSize], &spec[0]
, [maxVol] (float dB) -> float { return dB / maxVol; });
代码来自http://katyscode.wordpress.com/2013/01/16/cutting-your-teeth-on-fmod-part-4-frequency-analysis-graphic-equalizer-beat-detection-and-bpm-estimation
谢谢
最佳答案
原始代码:
if (maxVol != 0)
std::transform(&spec[0], &spec[sampleSize], &spec[0], [maxVol] (float dB) -> float { return dB / maxVol; });
Lambda:
[maxVol] (float dB) -> float { return dB / maxVol; }
替代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;
};
替换为完整代码:
if (maxVol != 0)
std::transform(&spec[0], &spec[sampleSize], &spec[0], percent_of(maxVol));
但是,此lambda非常简单,现在已内置到标准库中。 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);
}
关于c++ - lambda函数c++ 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22897452/