C++ STL ostream_iterator::ostream_iterator program sample

 

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++ STL ostream_iterator::ostream_iterator to construct an ostream_iterator that is initialized and delimited to write to the output stream in C++ programming

To show: How to use the C++  ostream_iterator to construct an ostream_iterator that is initialized and delimited to write to the output stream in C++ programming

 

// C++ STL ostream_iterator::ostream_iterator, constructor

#include <iterator>

#include <vector>

#include <iostream>

using namespace std;

 

int main(void)

{

// C++ STL ostream_iterator for stream cout

cout<<"Inserting & printing elements: "<<endl;

ostream_iterator<int> intOut(cout, "\n");

 

// insert data

*intOut = 12;

intOut++;

*intOut = 33;

intOut++;

int i;

 

// vector container

vector<int> vec;

 

// push/insert data into vec vector

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

vec.push_back(i);

 

cout<<"Operation: with and without delimiter..."<<endl;

// write elements to standard output stream

cout<<"Elements output without delimiter: ";

copy(vec.begin(), vec.end(), ostream_iterator<int> (cout));

cout<<endl;

 

// write elements with delimiter " " to output stream

cout<<"Elements output with delimiter: ";

copy(vec.begin(), vec.end(), ostream_iterator<int> (cout, " "));

cout<<endl;

return 0;

}

 

Output examples:

 

Inserting & printing elements:

12

33

Operation: with and without delimiter...

Elements output without delimiter: 101112131415

Elements output with delimiter: 10 11 12 13 14 15

Press any key to continue . . .

 

 

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