Using the ostream_iterator()

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 #include #include int iArr[] = {2, 3, 3, 4, 4, 5, 5, 6, 6};vector vecInt (iArr, iArr+9) ;ostream_iterator output (cout);unique_copy(vecInt.begin(), vecInt.end(), output);// output would be 23456

To display delimiters, use:

ostream_iterator 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 output_2 (ofile, " ABC ");unique_copy(vecInt.begin(), vecInt.end(), output_2); // 2 ABC 3 ABC 4 ABC 5 ABC 6 ABC
See also  5 Tips for Choosing the Right Medical Software for Your Practice

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist