Library: Algorithms
Function
Algorithm that assigns the same value to the elements in a given range
#include <algorithm> namespace std { template <class ForwardIterator, class T> void fill(ForwardIterator start, ForwardIterator finish, const T& value); template <class OutputIterator, class Size, class T> void fill_n(OutputIterator start, Size n, const T& value); }
The fill() and fill_n() algorithms are used to assign a value to the elements in a sequence. fill() assigns the value to all the elements designated by iterators in the range [start, finish).
The fill_n() algorithm assigns the value to all the elements designated by iterators in the range [start, start + n). fill_n() assumes that all iterators in the range [start, start + n) are dereferenceable, unless start is an insert iterator.
Type T must be Assignable, and Size must be convertible to an integral type.
fill() makes exactly finish - start assignments, and fill_n() makes exactly n assignments.
// // fill.cpp // #include <algorithm> #include <iostream> #include <vector> int main () { // Typedef for convenience. typedef std::vector<int, std::allocator<int> > vector; const vector::value_type arr[] = { 1, 2, 3, 4 }; // Set up two vectors. vector v1(arr, arr + sizeof arr / sizeof *arr); vector v2(v1.begin (), v1.end ()); // Set up one empty vector. vector v3; // Fill all of v1 with 9. std::fill(v1.begin (), v1.end (), 9); // Fill first 3 of v2 with 7. std::fill_n(v2.begin (), 3, 7); // Use insert iterator to fill v3 with 5 11's. std::fill_n(std::back_inserter (v3), 5, 11); // Copy all three to cout. std::ostream_iterator<vector::value_type, char, std::char_traits<char> > out(std::cout, " "); std::copy(v1.begin (), v1.end (), out); std::cout << std::endl; std::copy(v2.begin (), v2.end (), out); std::cout << std::endl; std::copy(v3.begin (), v3.end (), out); std::cout << std::endl; // Fill cout with 3 5's. std::fill_n(out, 3, 5); std::cout << std::endl; return 0; } Program Output
9 9 9 9 7 7 7 4 11 11 11 11 11 5 5 5
ISO/IEC 14882:1998 -- International Standard for Information Systems -- Programming Language C++, Section 25.2.5