I am trying to find a more efficient way to read an entire file into a vector of lines, defined as std::vector<std::string>
.
Currently, I have written the naive:
std::ifstream file{filepath};
std::vector<std::string> lines;
std::string line;
while(std::getline(file, line)) lines.push_back(line);
But feel as though the extra copy in push_back
and the vector reallocation for every line would be extremely detrimental to efficiency and am looking for a more modern c++ type of approach, such as using stream buffer iterators when copying bytes:
std::ifstream file{filepath};
auto filesize = /* get file size */;
std::vector<char> bytes;
bytes.reserve(filesize);
bytes.assign(std::istreambuf_iterator{file}, istreambuf_iterator{});
Is there any such way I could read a text file in by lines into a vector?