共用方式為


generate

Assigns the values generated by a function object to each element in a range.

template<class ForwardIterator, class Generator> 
   void generate( 
      ForwardIterator _First,  
      ForwardIterator _Last,  
      Generator _Gen 
   );

Parameters

  • _First
    A forward iterator addressing the position of the first element in the range to which values are to be assigned.

  • _Last
    A forward iterator addressing the position one past the final element in the range to which values are to be assigned.

  • _Gen
    A function object that is called with no arguments that is used to generate the values to be assigned to each of the elements in the range.

Remarks

The function object is invoked for each element in the range and does not need to return the same value each time it is called. It may, for example, read from a file or refer to and modify a local state. The generator's result type must be convertible to the value type of the forward iterators for the range.

The range referenced must be valid; all pointers must be dereferenceable and, within the sequence, the last position must be reachable from the first by incrementation.

The complexity is linear, with exactly (_Last – _First) calls to the generator being required.

Example

// alg_generate.cpp
// compile with: /EHsc
#include <vector>
#include <deque>
#include <algorithm>
#include <iostream>
#include <ostream>

int main( )
{
   using namespace std;

   // Assigning random values to vector integer elements
   vector <int> v1 ( 5 );
   vector <int>::iterator Iter1;
   deque <int> deq1 ( 5 );
   deque <int>::iterator d1_Iter;
   
   generate ( v1.begin ( ), v1.end ( ) , rand );
   
   cout << "Vector v1 is ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")." << endl;

   // Assigning random values to deque integer elements
   generate ( deq1.begin ( ), deq1.end ( ) , rand );

   cout << "Deque deq1 is ( " ;
   for ( d1_Iter = deq1.begin( ) ; d1_Iter != deq1.end( ) ; d1_Iter++ )
      cout << *d1_Iter << " ";
   cout << ")." << endl;
}
Vector v1 is ( 41 18467 6334 26500 19169 ).
Deque deq1 is ( 15724 11478 29358 26962 24464 ).

Requirements

Header: <algorithm>

Namespace: std

See Also

Reference

generate (STL Samples)

Standard Template Library