On 18.11.2013 08:40, Juha Nieminen wrote:
> Alf P. Steinbach <
alf.p.stein...@gmail.com> wrote:
>> I hate code that uses those named traversal algorithms.
>>
>> Instead I prefer the C++11 range based `for`, like
>>
>> for( auto elem : vec ) { blah blah }
>
> Which is great when you want to traverse only a sub-range, you want
> to traverse it backwards, you only have input iterators...
I agree, it's simply great. :-)
> Wait...
No, no, no; no need to wait for C++14.
For there is ample existing practice to draw on, e.g. Python programmers
do the above all the time, so that one already knows the general shape
of things.
It's just a matter of defining the requisite support machinery.
For example, for the task of reading from an input stream one can define
[code]
namespace cppx {
using std::istream;
using std::istream_iterator;
using std::ostream;
using std::ostream_iterator;
using std::string;
template< class Value >
class Istream_reader
// :public Non_copyable
{
private:
istream* p_stream_;
public:
typedef istream_iterator< Value > It;
auto begin() const -> It { return It( *p_stream_ ); }
auto end() const -> It { return It(); }
Istream_reader( istream& stream ): p_stream_( &stream ) {}
};
} // namespace cppx
[/code]
And then instead of code like
[code]
auto main() -> int
{
using namespace std;
typedef istream_iterator<string> Init;
typedef ostream_iterator<string> Outit;
cout << "? ";
vector<string> words;
copy( Init( cin ), Init(), back_inserter( words ) );
cout << words.size() << " words:" << endl;
copy( words.begin(), words.end(), Outit( cout, "\n" ) );
}
[code]
one can write, much more clear in IMHO, and certainly easier to code for
me!,
[code]
auto main() -> int
{
using namespace std;
using namespace cppx;
typedef Istream_reader<string> Reader;
cout << "? ";
vector<string> words;
for( auto s : Reader( cin ) ) { words.emplace_back( s ); }
cout << words.size() << " words:" << endl;
for( auto s: words ) { cout << s << "\n"; }
}
[/code]
which does the same, just more readable and writeable. ;-)
Cheers & hth.,
- Alf
PS: can the reader think of a simple support for "reverse range"?