No, because you need to keep the words until the last one is selected. Itβs harder to try marking back.
Also, you cannot use std::copy_backward because std::istream_iterator not bidirectional (input only).
std::deque perfect for this task. You could also use vector + back_inserter and copy from v.rbegin() to v.rend() in ostream_iterator .
In addition, the simplest string tokenization logic is expressed using istringstream .
Basically, it looks like you can't do much better.
The only religious thing is that I cannot stand using namespace even in the scope area.
My suggestion, with the same number of lines:
#include <algorithm> #include <iostream> #include <iterator> #include <sstream> #include <string> #include <vector> void output_tokens(const std::string& str) { typedef std::istream_iterator<std::string> in_iterator; typedef std::ostream_iterator<std::string> out_iterator; std::istringstream in(str); std::vector<std::string> buffer(in_iterator(in), (in_iterator())); std::copy(buffer.rbegin(), buffer.rend(), out_iterator(std::cout, "\n")); }
Important change: You need an extra pair of parentheses around in_iterator() to prevent the entire expression from being parsed as a function declaration. @ Steve Jessop's answer has the same problem. See this erroneous example to witness a drawing error message that occurs due to such confusion.
Alexandre C.
source share