C++11 Stream Iterators feel like Python
Found in Page 107, Section 4.5.3 Stream Iterators.
Let’s consider the tasks of:
- Reading a list of words from an input file
- Sorting them
- Eliminating duplicates and
- Writing them down into an output file
This can be done with the classic Unix shell commands:
|cat inputfile | sort | uniq > outputfile|
Let the code (and Stroustrup) speak:
- Reads two filenames from the standard input
- Opens one file for input
- Opens one file for output
- Associates one iterator to the input file
- Associates one iterator to the output file, along with a separator “\n”
- Creates a vector to contain strings and attach it to the iterator of the input file
- At this point the full file is read into memory and placed into the vector of strings
- Calls std::sort and in the process trigger the read.
- Once sorted, copies unique entries to the output file, using the output iterator
This can be rewritten a bit shorter (from the same Book, page 108) as:
infile = open(str(sys.argv))
outfile.writelines(sorted(list(set( infile.readlines() ))))
that returns the Zen of Python, by Tim Peters:
|Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea — let’s do more of those!
There is a lot in here that C++ and Python developers can agree upon.