Pages

Wednesday, March 10, 2010

Classical Output Iterator

Output iterator allow to write values into a sequence. The classical output iterator is ostream iterator, which is used to write values to the output stream:
#include <iostream>
#include <iterator>
#include <list>

int main (int argc, char * const argv[]) {
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

std::copy(&a[0], &a[10], &b[0]);

std::ostream_iterator<int> out(std::cout, " ");
std::copy(&a[0], &a[10], out);

std::cout << "\n";

return 0;
}
Output iterator allows to write value. For example if first is an output iterator, we can use *first=..., but it is not guarantee that we can obtain the value if will use *first.
More interesting practical use of the output iterators is the STL copy algorithm:
#include <iostream>
#include <iterator>
#include <list>

int main (int argc, char * const argv[]) {
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int b[10];

std::copy(&a[0], &a[10], &b[0]);
std::list<int> myList(&a[0], &a[10]);

std::ostream_iterator<int> out(std::cout, " ");
std::copy(myList.begin(), myList.end(), out);
std::cout << "\n";

return 0;
}
This program above copies an array a ino array b, then into a list. In the end, the list is copied into the output stream:

Loading program into debugger…
Program loaded.
run
[Switching to process 2192]
Running…
1 2 3 4 5 6 7 8 9 0 

Debugger stopped.
Program exited with status value:0.

No comments:

Post a Comment