Advanced File Handling with Streams in C++ - Printing from Containers
(Page 2 of 4 )
Probably from the first day that you started learning the C++ language, you've heard that you should start using the STL library, as it offers great containers. If you initially started with the C programming classes and you like arrays, I urge you also to get used to the vector container at least.
Often, you have a collection of types in a vector and you want to print them to the console (or a file) separated by a space, or every item in new line. Writing this can be done in just a line:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
std::vector<int> numbers;
numbers.push_back(97);
numbers.push_back(98);
numbers.push_back(99);
copy(numbers.begin(), numbers.end(), ostream_iterator<char>(cout, "...n"));
return 1;
}
We use the copy algorithm; it copies from our container to the stream. The real strength of this design is the ostream_class and its parameters. The class returns an iterator that will point out where to print the content between the first two iterators of the copy. In addition, the ostream_iterator class is highly customizable, with inputs like output format, where to put it, and what delimiter will be used between the members.
The template argument must be one for which the insertion operator is declared. As long as all of this is completed, you can call this method even for your own custom class, as the operator<< will be used to copy the streams from the container to the output stream. The result in the upper case looks impressive; we just converted the int values into their ASCI chars.
a...
b...
c...
Press any key to continue . . .
Next: Reading Inside a Container >>
More C++ Articles
More By Gabor Bernat