I have the following code in C++:
string str="a b c";
stringstream sstr(str);
vector<string> my_vec((istream_iterator<string>(sstr)),
istream_iterator<string>());
Is there any way to save the use of sstr, something like the following?
vector<string> my_vec((istream_iterator<string>(str)),
istream_iterator<string>());
istream_iterator‘s argument needs to be able to bind to a non-const reference, and a temporary cannot. However, (as Alf points out),ostreamhappens to have a function,flush(), that returns a non-const reference to itself. So a possibility is:Though that’s an eye-sore. If you’re concerned about having too many lines, then use a function:
Giving:
This is even cleaner than what you’d get even if you could shorten your code, because now what is being done is not expressed in code but rather the name of a function; the latter is much easier to grasp.
*Of course, we can add boiler-plate code to do silly things:
Giving:
But this is just as ugly as the first solution.