我正在读取一个包含大约170万行的文本文件,每行都由3个整数组成。我面临的问题是,循环遍历并将整数存储到向量中需要约30秒的时间。
以下是我写的代码:
以下是我写的代码:
std::ifstream finVertices("Phantom Data/FA_vertices.txt", std::ios::in);
if (!finVertices)
{
std::cerr << "Can not open verticies.txt" << std::endl;
}
std::cout << "Loading verticies" << std::endl;
std::string verticesLineBuffer;
while (std::getline(finVertices, verticesLineBuffer))
{
std::istringstream voxelStringCoordinates(verticesLineBuffer);
GLfloat x, y, z;
voxelStringCoordinates >> x >> y >> z;
vertices.push_back(glm::vec3(y, z, x));
}
finVertices.close();
文本文件内容示例:
297 13 164
297 13 165
297 14 164
297 14 165
298 13 164
298 13 165
问题:如何从txt文件中提高读取的效率?
编辑:感谢您的帮助,通过您的帮助我解决了这个问题。以下是代码:
std::ifstream is(fileName, std::ifstream::binary);
if (is) {
is.seekg(0, is.end);
int length = is.tellg();
is.seekg(0, is.beg);
char* buffer = new char[length];
is.read(buffer, length);
is.close();
for (unsigned int i = 0; i < is.gcount(); i++)
{
// here can get access to each indiviual character
}
vertices
是否有足够的预留空间,以免需要重新分配内存? - Eljaymmap
将整个文件映射到内存中,然后迭代它,使用std::from_chars
逐个提取整数值。 - Sam Varshavchik