The fill() Algorithm

The algorithm fill() is declared in as follows:

 void fill(ForwardIterator f, ForwardIterator l, const T&);

The arguments f and l mark the sequence’s beginning and end, respectively. fill() fills the elements in the sequence with the fixed value T. This algorithm is useful when you want to initialize or reinitialize a sequence with a fixed value. For example, to initialize a char array, use fill() as follows:

 #include char *p = new char[100];std::fill(p, p+100, ''); // zero all characters

This is similar to calling memset(p, 0, 100). Note however, that fill() respects object semantics, unlike memset(). Therefore, you can use it to reinitialize a sequence of objects as well:

 #include #include #include std::vector < std::string> vs(100); std::fill(vs.begin(), vs.end(), "greetings!"); 

The vector vs initially contains 100 empty strings. fill() assigns a new value: “greetings!” to all the strings in the vector.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: