STL: fill,fill_n,generate,generate_n

fill

Assigns the same new value to every element in a specified range.

template<class ForwardIterator, class Type>
   void fill(
      ForwardIterator _First, 
      ForwardIterator _Last, 
      const Type& _Val
   );

fill_n

Assigns a new value to a specified number of elements in a range beginning with a particular element.

template<class OutputIterator, class Size, class Type>
   void fill_n(
      OutputIterator _First, 
      Size _Count, 
      const Type& _Val
   ); 

注:_Count必须小于等于_Last-_First.

此外,对于char* 或者wchar_t*的数组,最好是使用memset或wmemset。

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 
   );

例如,用随机数值填充vector。

template<class T>
struct display
{
    void operator()(const T& val){
        cout<<val<<' ';
    }
};

int rand100(){
    return rand()%100;
}

int main()
{
    vector<int> vec(5);
    srand(time(0));
    generate(vec.begin(),vec.end(),rand100);
    cout<<"vector: ";
    for_each(vec.begin(),vec.end(),display<int>());
    cout<<endl;

    getchar();
}

generate_n

Assigns the values generated by a function object to a specified number of elements in a range and returns to the position one past the last assigned value.

template<class OutputIterator, class Diff, class Generator>
   void generate_n(
      OutputIterator _First, 
      Diff _Count, 
      Generator _Gen
   );

此外,<numeric>中的iota可以使用递增序列填充一个指定的区域。这个函数好像是新增的,不晓得是不是标准STL中的成员。

iota

Stores a starting value, beginning with the first element and filling with successive increments of that value ( _Value++) in each of the elements in the interval [_First, _Last).

template<class ForwardIterator, class Type> 
   void iota( 
      ForwardIterator _First,  
      ForwardIterator _Last, 
      Type _Value  
   );
原文地址:https://www.cnblogs.com/freewater/p/2947614.html