If I want to fill a vector of strings with lines from a file in C++, is it a good idea to use push_back
with std::move
?
{
std::ifstream file("E:\\Temp\\test.txt");
std::vector<std::string> strings;
// read
while (!file.eof())
{
std::string s;
std::getline(file, s);
strings.push_back(std::move(s));
}
// dump to cout
for (const auto &s : strings)
std::cout << s << std::endl;
}
Or is there some other variant where I would simply append a new string instance to the vector and get its reference?
E.g. I can do
std::vector<std::string> strings;
strings.push_back("");
string &s = strings.back();
But I feel like there must be a better way, e.g.
// this doesn't exist
std::vector<std::string> strings;
string & s = strings.create_and_push_back();
// s is now a reference to the last item in the vector,
// no copying needed