C++ STL algorithm, fill_n() program sample

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the C++ fill_n() to assign a new value to a specified number of elements in a range beginning with a particular element in C++ programming

To show: How to use the C++ algorithm, fill_n() to assign a new value to a specified number of elements in a range beginning with a particular element in C++ programming

// C++ STL algorithm, fill_n()

#include <vector>

#include <algorithm>

#include <iostream>

using namespace std;

int main(void)

{

// vector container

vector <int> vec;

// vector iterator

vector <int>::iterator Iter1;

int i;

// pushing data, constructing vec vector

for(i = 10; i <= 20; i++)

vec.push_back(i);

// print the data

cout<<"vec vector data: ";

for(Iter1 = vec.begin(); Iter1 != vec.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

// do the fill_n() operation, fill the last 3 positions for 6 position with a value of 9

cout<<"\nOperation: fill_n(vec.begin() + 3, 6, 9)\n";

fill_n(vec.begin() + 3, 6, 9);

// print the result

cout<<"Modified vec vector data: ";

for(Iter1 = vec.begin(); Iter1 != vec.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

return 0;

}

Output examples:

vec vector data: 10 11 12 13 14 15 16 17 18 19 20

Operation: fill_n(vec.begin() + 3, 6, 9)

Modified vec vector data: 10 11 12 9 9 9 9 9 9 19 20

Press any key to continue . . .