在《STL源码剖析》中看到了Pow函数在STL中的实现,感觉程序写的非常巧妙。列出源码
template <class T>
inline T identity_element(plus<T>){
return T(0);
}
template <class T>
inline T identity_element(multiplies<T>){
return T(1);
}
template <class T,class Integer>
inline T power_this(T x, Integer n){
return power_this(x, n, multiplies<T>());
}
template <class T,class Integer, class MonoidOperation>
T power_this(T x, Integer n, MonoidOperation op){
if (n == 0)
return identity_element(op);
else{
while ((n & 1) == 0){
n >>= 1;
x = op(x, x);
}
T result = x;
n >>= 1;
while (n != 0){
x = op(x, x);
if ((n & 1) != 0)
result = op(result, x);
n >>= 1;
}
return result;
}
}
identity_element(op)为取“证同元素”。所谓“运算op的证同元素”,意思是数值A若与该元素做op运算,会得到A自己。加法的证同元素为0,因为任何元素加上0仍为自己。乘法的证同元素为1,因为任何元素乘以1仍为自己。