First of all, you generally want to avoid a loop of the form while (file.good())
.
If you're going to do this with a loop, you generally want to use the return from getline
as your condition:
std::string line;
while (std::getline(file, line)) {
vec.push_back(line);
}
This tries to read a line, then if (and only if) that succeeds, adds the line to the vector.
Getting to the question you asked though: yes and no, but mostly no.
You have to create a string object, then read the data into that string object. The string object has to exist before you can read data into it.
If you're concerned mostly with making the code look as neat and tidy as possible, you can hide the temporary string object, such as by using a proxy. Using that, you could write your code something like this:
std::vector<std::string> vec{ std::istream_iterator<line>(infile),
std::istream_iterator<line>() };
This hides the temporary string object, but doesn't really eliminate it.
It's also possible you're concerned with the inefficiency of reading the data into one string object, then having to copy that string object into the vector (then destroying the first string object).
If that's your real concern, you probably want to use std::move
on the source string to move the strings into the vector instead of copying them. Instead of copying the entire content of the string from one place to another, this will normally just copy a pointer to the data, set the originating string to know that it's now empty, and it'll be done--fast and cheap, regardless of how long the string might be.
The exception here is that most modern implementations of std::string
have what's called a "short string optimization". This means if the string you're storing is short enough (typically around 15 characters or less), it gets stored in the string object itself instead of being allocated separately, with a pointer to that data in the string object. In this case, moving a string object still involves copying all the data it contains--but pretty much by definition, this is limited to short strings, were copying all the data is fairly inconsquential.