//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;
}
STL示例08(ptr_fun和random_shuffle搭配使用)
最新推荐文章于 2023-01-08 10:52:54 发布