
上QQ阅读APP看书,第一时间看更新
How to do it...
In this section, we will read a stream of words from the standard input. All unique words are put into an std::set instance. This way we can then enumerate all unique words from the stream.
- We will use several different STL types, for which we need to include multiple headers.
#include <iostream>
#include <set>
#include <string>
#include <iterator>
- In order to spare us some typing, we will declare that we are using namespace std:
using namespace std;
- Now we're already writing the actual program, which begins with the main function instantiating an std::set which stores strings.
int main()
{
set<string> s;
- The next thing to do is to get the user input. We're just reading from standard input, and do that using the handy istream_iterator.
istream_iterator<string> it {cin};
istream_iterator<string> end;
- Having a pair of begin and end iterators, which represent the user input, we can just fill the set from it using an std::inserter.
copy(it, end, inserter(s, s.end()));
- That's already it. In order to see what unique words we got from standard input, we just print the content of our set.
for (const auto word : s) {
cout << word << ", ";
}
cout << '\n';
}
- Let's compile and run our program with the following input. We get the following output for the preceding input, where all duplicates are stripped out, and the words which were unique, are sorted alphabetically.
$ echo "a a a b c foo bar foobar foo bar bar" | ./program
a, b, bar, c, foo, foobar,