如何将巨大的文件读取到向量或数组中

How to read huge file into vector or array

本文关键字:向量 数组 读取 文件 巨大      更新时间:2023-10-16

我编写了将文件读取为矢量的代码。但是速度非常慢。(阅读大约43万行需要12秒)我的代码出了什么问题?当我在C#中做同样的事情时,只需要0.5~1秒。

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
bool getFileContent(string fileName, vector<string> &vecOfStrs)
{
ifstream in(fileName.c_str());
if (!in)
{
std::cerr << "Cannot open the File : " << fileName << std::endl;
return false;
}
string str;
while (getline(in, str))
{
if (str.size() > 0)
{
vecOfStrs.push_back(str);
}
}
in.close();
return true;
}
int main()
{
string my_file_path = "C:/Users/user/Desktop/myfile.txt";
vector<string> lines;
bool result = getFileContent(my_file_path, lines);
if (result)
{
cout << lines.capacity() << endl;
}
}

我假设您正在使用Visual Studio开发应用程序。对优化is/O2 执行以下步骤

1> 项目属性-->配置属性-->C/C++-->代码生成-->基本运行时检查=默认

2> 项目属性-->配置属性-->C/C++-->优化-->优化=最大优化(最快速度)(/O2)

它将使您的程序在运行时得到最大程度的优化。如果它仍然不好,我认为你应该数一下这个链接文件中的行数如何在C++中计算文件的行数?

并为初始矢量的容量保留这个数字。

希望它能解决你的问题。这是我的解决方案

ifstream in("result_v2.txt");
vector<string> lines;
string str;
while (std::getline(in, str))
{
if (str.size() > 0)
{
lines.push_back(str);
}
}
in.close();