C++ STL algorithm, fill() program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

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() to assign the same new value to every element in a specified range in C++ programming

To show: How to use the C++ algorithm, fill() to assign the same new value to every element in a specified range in C++ programming

 

// C++ STL algorithm, fill()

#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 in range, constructing 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() operation, fill the last 4 positions with a value of 9

cout<<"\nOperation: fill(vec.begin() + 4, vec.end(), 9)"<<endl;

fill(vec.begin() + 4, vec.end(), 9);

// print the data

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(vec.begin() + 4, vec.end(), 9)

Modified vec vector data: 10 11 12 13 9 9 9 9 9 9 9

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index