用来生成元素,并填充到一个序列中
generate:
1 template <class ForwardIterator, class Generator> 2 void generate ( ForwardIterator first, ForwardIterator last, Generator gen ) 3 { 4 while (first != last) { 5 *first = gen(); 6 ++first; 7 } 8 }
Generator gen生成器,是一个不接受参数,且有返回参数的函数,first和last是生成的范围。
generate_n:
void generate_n (OutputIterator first, Size n, Generator gen);
first插入起始位置,n插入元素个数,gen元素生成器、
1 #include<iostream> 2 #include<vector> 3 #include<algorithm> 4 #include<time.h> 5 #include <iterator> 6 using namespace std; 7 8 int nextNum() { 9 static int n = 1; 10 return n++; 11 12 } 13 14 class Range_generate{ 15 private: 16 int m_Value; 17 public: 18 Range_generate(int value){m_Value=value;} 19 int operator()(){ 22 return m_Value++;} 23 }; 24 25 int main(){ 26 for(int i=0;i<5;i++) 27 cout<<nextNum()<<" "; 28 srand((unsigned int) time(NULL)); 29 vector<int> array(10,4); 30 cout<<endl; 31 int length=array.size(); 32 cout<<length<<endl; 33 generate(array.begin(),array.end(),[]{return rand()%10;}); 34 for(vector<int>::iterator ptr=array.begin();ptr!=array.end();){ 35 cout<<*ptr<<" "; 36 ptr++; 37 } 38 cout<<endl; 39 generate(array.begin(),array.end(),Range_generate(1)); 40 ostream_iterator<int> screen(cout," "); 41 copy(array.begin(),array.end(),screen); 42 system("pause"); 43 return 0; 44 }
时间: 2024-10-25 21:01:03