Initialising std::vector from a sequence using std::istringstream
This code:
#include <vector>
#include <string>
#include <iterator>
#include <sstream>
#include <iostream>
int main()
{
std::vector<std::string>
v(std::istream_iterator<std::string>(std::istringstream("abc bca cab")),
std::istream_iterator<std::string>());
std::cout << "abc = " << *v.begin() << std::endl;
}
compiles and works. However, I have problems with variations. When I take
std::istringstream("abc bca cab")
out and declare it as a separate variable, to make the code look like this:
//...
int main()
{
std::istringstream lst("abc bca cab");
std::vector<std::string> v(std::istream_iterator<std::string>(lst),
std::istream_iterator<std::string>());
std::cout << "abc = " << *v.begin() << std::endl;
}
the compiler complains like this:
error C2228: left of '.begin' must have class/struct/union
(had I not used the vector variable by commenting out the line where it is
used (with *v.begin()), the code would compile and the compiler would warn
prototyped function not called (was a variable definition intended?)
with reference to the vector initialisation).
To make this variation compile, I declared and initialised the vector
separately:
// ...
int main()
{
std::istringstream lst("abc bca cab");
std::vector<std::string> v;
v.assign(std::istream_iterator<std::string>(lst),
std::istream_iterator<std::string>());
std::cout << "abc = " << *v.begin() << std::endl;
}
which compiles and works.
This rather puzzles me. Ideally I would want to initialise the vector using
its constructor, yet declare the std::istringstream variable separately. Am I
missing something?
Thank you.
Paul