dcsimg
Login | Register   
LinkedIn
Google+
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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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
Thanks for your registration, follow us on our social networks to keep up-to-date