我必须加载大文件(几GB)的数据,我想加载它们到二维向量。下面的代码可以完成这项工作,但它非常缓慢。更具体地说,目标是获得第二列中的值等于索引(_lh,_sh)的所有行。然后排除第4列值与第1行和第1行相同的行。 现在,我是新来的c + +和我平常Python代码(已经有这个问题的工作代码)。但我需要它尽可能快,所以我试图将我的Python代码重写为C++。但现在它比Python慢(并且只能将数据传递给矢量)......所以在我继续之前,我想改进它。 从我发现的类似问题中,问题将是动态向量,.push_back()和getline()。如何加快文本文件加载到多向量
对于在类似问题中提到的映射和块加载,我感到非常困惑,所以我不能根据这些改变代码。
你能帮我优化这段代码吗?
谢谢。
#include <iostream>
#include <sstream>
#include <fstream>
#include <array>
#include <string>
#include <vector>
using namespace std;
int pixel(int radek, int sloupec, int rozmer = 256) {
int index = (radek - 1) * rozmer + sloupec;
int index_lh = (index - rozmer - 1);
int index_sh = (index - rozmer);
int index_ph = (index - rozmer + 1);
int index_l = (index - 1);
int index_p = (index + 1);
int index_ld = (index + rozmer - 1);
int index_sd = (index + rozmer);
int index_pd = (index + rozmer + 1);
array<int, 9> index_all = { {index, index_lh, index_sh, index_ph, index_l, index_p, index_ld, index_sd, index_pd } };
vector<vector<string>> Data;
vector<string> Line;
string line;
for (int m = 2; m < 3; m++) {
string url = ("e:/TPX3 - kalibrace - 170420/ToT_ToA_calib_Zn_" + to_string(m) + string(".t3pa"));
cout << url << endl;
ifstream infile(url);
if (!infile)
{
cout << "Error opening output file" << endl;
system("pause");
return -1;
}
while (getline(infile, line))
{
Line.push_back(line);
istringstream txtStream(line);
string txtElement;
vector<string> Element;
while (getline(txtStream, txtElement, '\t')){
Element.push_back(txtElement);
}
Data.push_back(Element);
}
}
cout << Data[1][0] << ' ' << Data[1][1] << ' ' << Data[1][2] << endl;
return 0;
}
int main()
{
int x = pixel(120, 120);
cout << x << endl;
system("pause");
return 0;
}
Boost有一些库,用于*非常*快速的读/写I/O操作。如果你可以使用它们当然。 – Rakete1111
不是'for(int m = 2; m <3; m ++)'是否意味着循环只进行一次?那是故意的吗? – InternetAussie
什么是慢?从文件加载到二维数组还是搜索? – arynaq