generate和generate_n算法
generate和generate_n算法分类: 数据结构与算法 C++& API算法目的用发生器对容器进行填充templatetypename ForwardIterator, typename Generator>void generate(ForwardIterator first, ForwardIterator last, Generator
算法目的用发生器对容器进行填充
template<typename ForwardIterator, typename Generator>
void generate(ForwardIterator first, ForwardIterator last, Generator gen){
for ( ; first != last; ++first)
*first = gen();
}
算法目的用发生器对容器从first开始进行填充n次
template<typename OutputIterator, typename Size, typename Generator>
OutputIterator generate_n(OutputIterator first, Size n, Generator gen) {
for ( ; n > 0; --n, ++first)
*first = gen();
return first;
}
当然为了使用这两个算法,你还要写一个发生器.随便举个例子:
struct Gen{
int operator()(){
return rand();//产生随机数的函数
}
};
boost例子
#include <list>
#include <algorithm>
#include <cstdlib>
#include <cassert>
#include <iostream>
#include "windows.h"
#include "time.h"
#include <boost/algorithm/minmax.hpp>
#include <boost/algorithm/minmax_element.hpp>
int main()
{
using namespace std;
// Demonstrating minmax()
boost::tuple<int const&, int const&> result1 = boost::minmax(1, 0);
assert( result1.get<0>() == 0 );
assert( result1.get<1>() == 1 );
// Demonstrating minmax_element()
list<int> L;
typedef list<int>::const_iterator iterator;
srand(time(NULL));
generate_n(front_inserter(L), 1000, rand);
pair< iterator, iterator > result2 = boost::minmax_element(L.begin(), L.end());
cout << "The smallest element is " << *(result2.first) << endl;
cout << "The largest element is " << *(result2.second) << endl;
assert( result2.first == std::min_element(L.begin(), L.end()) );
assert( result2.second == std::max_element(L.begin(), L.end()) );
Sleep(11111111);
}
更多推荐
所有评论(0)