STL中对Pow函数的实现

在《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仍为自己。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++,我们可以利用队列实现链式基数排序。这里介绍一个利用STL的队列实现链式基数排序的方法。 ```cpp #include <iostream> #include <queue> #include <cmath> using namespace std; // 获取一个数字的某一位数字 int getDigit(int number, int digit) { return (number / static_cast<int>(pow(10, digit - 1))) % 10; } // 链式基数排序 void radixSort(int arr[], int size, int digit) { // 创建 10 个桶 queue<int> bucket[10]; // 按照每一位数字进行排序 for (int i = 1; i <= digit; i++) { // 把数据放入桶 for (int j = 0; j < size; j++) { int num = getDigit(arr[j], i); bucket[num].push(arr[j]); } // 把桶的数据放回原数组 int index = 0; for (int j = 0; j < 10; j++) { while (!bucket[j].empty()) { arr[index++] = bucket[j].front(); bucket[j].pop(); } } } } int main() { int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; int size = sizeof(arr) / sizeof(arr[0]); radixSort(arr, size, 3); for (int i = 0; i < size; i++) { cout << arr[i] << " "; } cout << endl; return 0; } ``` 在代码,我们首先定义了一个 `getDigit` 函数,用于获取一个数字的某一位数字。然后定义了 `radixSort` 函数,用于进行链式基数排序。在函数,我们首先创建了 10 个桶,然后按照每一位数字进行排序,具体实现方法是把数据放入相应的桶,然后把桶的数据放回原数组。最后,在 `main` 函数,我们创建了一个数组 `arr`,并调用 `radixSort` 函数进行排序。最后输出排序后的结果。 需要注意的是,这里我们只引入了队列的库,而没有引入链表等其他库,因为队列是链表的一种特殊形式,可以用来实现链式存储。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值