如何将巨大的文件读取到向量或数组中
How to read huge file into vector or array
我编写了将文件读取为矢量的代码。但是速度非常慢。(阅读大约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();
相关文章:
- 如何在向量数组中插入元素?
- 不同大小的向量数组的大小 cpp
- 很好的语法来获取对向量/数组数据的大小引用?
- 指向 c++ 中的向量数组并将其发送到函数的指针
- 初始化向量数组,其中每个向量的大小为 0
- 在这里,当我们比较 if(vc[i]==vc1[i]) 时,它是向量数组. 实际上比较的值是多少,
- 如何使用结构体的向量数组?
- C++:向量数组
- 在C++中通过引用传递向量数组
- 向量数组"Cannot access memory at address"
- 构造不同类型的C++向量数组
- 向量数组的均值和众数 - 如何对函数进行较小的改进
- C++:初始化(新)一个不同初始大小的向量数组
- 五个中三个最大参数的平均值,不使用排序算法或向量/数组
- 销毁C++中的向量数组
- 继承向量/数组/列表并更改其大小
- 如何输出属于向量数组的结构字符串
- 如何通过引用传递向量数组
- 在向量数组中获得前五个最大的结果
- 为什么"new vector<int>[5]"不创建向量数组?