STL示例08(ptr_fun和random_shuffle搭配使用)

//STL示例 发生器函数对象
#include <iostream>
#include <stdlib.h>    // Need random(), srandom()
#include <time.h>      // Need time()
#include <algorithm>   // Need random_shuffle()
#include <vector>      // Need vector
#include <functional>  // Need ptr_fun()
#include<iterator>
using namespace std;

int iarray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
vector<int> v(iarray, iarray + 10);

void Display(vector<int>& vr, const char *s);
unsigned int RandInt(unsigned int n);

int main()
{
	srand( time(NULL) );  // 初始化随机数发生器
	Display(v, "Before shuffle:");
	
	//模版类pointer_to_unary_function
	//将RandInt的结果转换为pointer_to_unary_function<unsigned int, unsigned int>类型
	pointer_to_unary_function<unsigned int, unsigned int> ptr_RandInt = ptr_fun(RandInt);  
	//再利用转换后的ptr_RandInt做随机发生器种子打乱容器元素排序
	//改成random_shuffle(v.begin(), v.end(), pointer_to_unary_function<unsigned int, unsigned int>(RandInt));也是一样
	random_shuffle(v.begin(), v.end(), ptr_RandInt);
	Display(v, "After shuffle:");
	return 0;
}

//显示容器元素
void Display(vector<int>& vr, const char *s)
{
	cout << endl << s << endl;
	copy(vr.begin(), vr.end(), ostream_iterator<int>(cout, " "));
	cout << endl;
}

unsigned int RandInt(const unsigned int n)
{
	cout<<"被调用了"<<n<<"次"<<endl;//n输出从1到9,详见random_shuffle实现
	return rand() % n;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值