You should have a knowledge of vectors and vector iterators
First off, what does fill() do?
Well, fill() does exactly what it says on the tin. It fills a vector with a specific value.
Before we begin, here is the general syntax for using the fill function:
fill (<where to begin filling from>, <where to stop filling>, <what to fill with>);
What do we need to include?
#include <iostream> // output the values to see what's going on #include <algorithm> // our algorithm library #include <vector> // we need a vector to use the algorithms on using namespace std; // vectors and output
Next, we need to begin our int main () function. I'm gonna assume you know how to do this, and move on
Now we need to declare a vector and a vector iterator:
vector <int> myVec; // create a vector called myVec vector <int> :: iterator it; // create a vector iterator called it
And then we want to fill and print the vector. Easy enough:
for (int i = 0; i < 9; ++i)
myVec.push_back(i); // fill the vector with some values
cout << "Before fill: ";
for (it = myVec.begin(); it != myVec.end(); ++it)
cout << *it << " "; // print the contents of myVec
Now for our "fill" function.
fill (myVec.begin(), myVec.end(), 5); // fill all values with the value '5'
All we need to do now is output the contents of the vector, and exit the program:
cout << endl << "After fill: ";
for (it = myVec.begin(); it != myVec.end(); ++it)
cout << *it << " "; // print the contents of myVec again
cin.get (); // pause
return EXIT_SUCCESS; // everything went OK
Here's the complete code, for those of you who learn better by example alone:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main ()
{
vector <int> myVec; // create a vector called myVec
vector <int> :: iterator it; // create a vector iterator called it
for (int i = 0; i < 9; ++i)
myVec.push_back(i); // fill the vector with some values
cout << "Before fill: ";
for (it = myVec.begin(); it != myVec.end(); ++it)
cout << *it << " "; // print the contents of myVec
fill (myVec.begin(), myVec.end(), 5); // fill all values with the value '5'
cout << endl << "After fill: ";
for (it = myVec.begin(); it != myVec.end(); ++it)
cout << *it << " "; // print the contents of myVec again
cin.get (); // pause
return EXIT_SUCCESS; // everything went OK
}









MultiQuote




|