Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
Dec 13, 2004

Using the ostream_iterator()

The ostream_iterator() is useful for reading the elements of a container to the standard output or to a file. However, because this iterator works in conjunction with STL algorithms, it allows you to perform a variety of actions besides merely reading the elements of a container.

Suppose you have a vector of int and you want to display only the unique numbers stored in the vector:


#include <vector>
#include <algorithm>
#include <iterator>


int iArr[] = {2, 3, 3, 4, 4, 5, 5, 6, 6};

vector <int>vecInt (iArr, iArr+9) ;

ostream_iterator<int> output (cout);
unique_copy(vecInt.begin(), vecInt.end(), output);// output would be 23456
To display delimiters, use:

ostream_iterator<int> output_1 (cout, " ABC ");
unique_copy(vecInt.begin(), vecInt.end(), output_1); // 2 ABC 3 ABC 4 ABC 5 ABC 6 ABC
Remember that ostream_iterator() takes a char* as a delimiter, so it must be null terminated.

To write the output to a file, pass an object of the ofstream class to the ostream_iterator:


ofstream ofile ("Test.txt")

ostream_iterator<int> output_2 (ofile, " ABC ");
unique_copy(vecInt.begin(), vecInt.end(), output_2); // 2 ABC 3 ABC 4 ABC 5 ABC 6 ABC
Saurabh Ramya
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap