In a quest to optimize file reading into an std::vector
The solution lies in the use of iterators. By creating an input streambuf iterator and using it to construct a vector, the file's contents can be directly assigned to the vector without the need for intermediate copies. The following code snippet illustrates this approach:
#include<iterator> std::ifstream testFile("testfile", std::ios::binary); std::vector<char> fileContents((std::istreambuf_iterator<char>(testFile)), std::istreambuf_iterator<char>());
For performance concerns, reserving space in the vector prior to assignment can prevent reallocations:
std::vector<char> fileContents; fileContents.reserve(fileSize); fileContents.assign(std::istreambuf_iterator<char>(testFile), std::istreambuf_iterator<char>());
The above is the detailed content of How to Efficiently Read a File into a `std::vector` Without Overhead?. For more information, please follow other related articles on the PHP Chinese website!