The fill and Fill_n functions are part of the 12th generic algorithm for C + + primer and call them generation and mutation algorithms, meaning that these two functions can only operate on elements that already exist in the input range . Attempting to fill_n an empty container can result in a serious run-time error, so when writing to an element, check to see if the target is large enough to store the element to be written.
The fill function is to give the element of an interval a Val value. Function parameters: Fill (Vec.begin (), Vec.end (), Val); Val is the value that will be replaced.
The functions of the Fill_n function are: An iterator, a counter, and a value. The function starts with the element that the iterator points to, setting the specified number of elements to the given value.
Note: The Fill_n function cannot be called on an empty container without elements, but can be improved by the following method.
Fill_n (Vec.begin (), 10,val);
To ensure that the algorithm has enough elements to store the output data, we use the Insert iterator , insert iterator, which is an iterator that can add elements to the underlying container.
The program that uses Back_inserter needs to include the header file #include<iterator>, and the above program is rewritten as:
1 #include <iterator> 2 vector<int> VEC; // define an empty container 3 fill_n (Back_inserter (VEC), ten val);
In this program, each write value of the Fill_n () function is implemented by an insert iterator produced by Back_inserter. The effect is equivalent to push_back on the VEC, adding 10 elements at the end of the VEC.
C + + fill () and Fill_n () function usage (GO)