I have a question about the following code that tokenizes a string (separates the tokens by space).
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string s="And I feel fine ...";
istringstream ss(s);
vector<string> tokens{istream_iterator<string>(ss),{}};
for(auto& elem: tokens)
cout << elem << endl;
}
This works perfectly fine. On the other hand, if I try to pass a temporary istringstream
object to
istream_iterator
(3-rd line inside main
), such as
vector<string> tokens{istream_iterator<string>(istringstream(s)),{}};
I am getting a compile-time error
error: no matching conversion for functional-style cast from 'istringstream' (aka 'basic_istringstream<char>') to 'istream_iterator<string>'
I believe it is because I cannot bound a temporary rvalue to a non-const lvalue reference, and the constructor of istream_iterator
takes a reference as a parameter. Is there any way of constructing an istream_iterator<string>
from a temporary? I cannot use std::ref
on a temp object either...
Thanks!