O'Reilly logo

Essential C++ by Stanley B. Lippman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.10. Using the iostream Iterators

Imagine that we have been given the task of reading a sequence of string elements from standard input, storing them into a vector, sorting them, and then writing the words back to standard output. A typical solution looks like this:

#include <iostream> 
#incluse <string> 
#include <vector> 
#include <algorithm> 
using namespace std; 

int main() 
{ 
    string word; 
    vector<string> text; 

    // ok: let's read each word in turn until done 
    while ( cin >> word ) 
            text.push_back( word ); 

    // ok: sort it 
    sort( text.begin(), text.end() ); 

    // ok: let's write them back 
    for ( int ix = 0; ix < text.size(); ++ix ) 
          cout << text[ ix ] << ' '; 
} 

The standard library defines both input and output iostream iterator classes, called istream_iterator ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required