fill_n
Syntax:
#include <algorithm> #include <algorithm> iterator fill_n( iterator start, size_t n, const TYPE& val );
The fill_n() function is similar to (C++ I/O) fill(). Instead of assigning val to a range of elements, however, fill_n() assigns val to the first n elements starting at start.
For example, the following code uses fill_n() to assign -1 to the first half of a vector of integers:
vector<int> v1; for( int i = 0; i < 10; i++ ) { v1.push_back( i ); } cout << "Before, v1 is: "; for( unsigned int i = 0; i < v1.size(); i++ ) { cout << v1[i] << " "; } cout << endl; fill_n( v1.begin(), v1.size()/2, -1 ); cout << "After, v1 is: "; for( unsigned int i = 0; i < v1.size(); i++ ) { cout << v1[i] << " "; } cout << endl;
When run, this code displays:
Before, v1 is: 0 1 2 3 4 5 6 7 8 9 After, v1 is: -1 -1 -1 -1 -1 5 6 7 8 9
Related topics: