gpt4 book ai didi

c++ - 读取文本文件和使用二维 vector

转载 作者:太空狗 更新时间:2023-10-29 20:02:47 25 4
gpt4 key购买 nike

我正在使用下面的方法读取一个大的空格分隔的 txt 文件(大约 900 Mb)。我花了 879 秒将数据加载到内存中。请问有没有更高效的读取txt文件的方法?

另一个相关的问题是:使用 2D vector 存储如此庞大的数据集是个好主意吗?

这是我的代码

void Grid::loadGrid(const char* filePathGrid)
{
// 2D vector to contain the matrix
vector<vector<float>> data;

unsigned nrows, ncols;
double xllcorner, yllcorner;
int cellsize, nodataValue;
const int nRowHeader = 6;
string line, strtmp;

ifstream DEMFile;
DEMFile.open(filePathGrid);
if (DEMFile.is_open())
{
// read the header (6 lines)
for (int index = 0; index < nRowHeader; index++)
{
getline(DEMFile, line);
istringstream ss(line);
switch (index)
{
case 0:
while (ss >> strtmp)
{
istringstream(strtmp) >> ncols;
}
break;
case 1:
while (ss >> strtmp)
{
istringstream(strtmp) >> nrows;
}
break;
case 2:
while (ss >> strtmp)
{
istringstream(strtmp) >> xllcorner;
}
break;
case 3:
while (ss >> strtmp)
{
istringstream(strtmp) >> yllcorner;
}
break;
case 4:
while (ss >> strtmp)
{
istringstream(strtmp) >> cellsize;
}
break;
case 5:
while (ss >> strtmp)
{
istringstream(strtmp) >> nodataValue;
}
break;
}
}

// Read in the elevation values
if (ncols * nrows > 0)
{
// Set up sizes. (rows x cols)
data.resize(nrows);
for (unsigned row = 0; row < nrows; ++row)
{
data[row].resize(ncols);
}

// Load values in
unsigned row = 0;
while (row < nrows)
{
getline(DEMFile, line);
istringstream ss(line);
for (unsigned col =0; col < ncols; col++)
{
ss >> data[row][col];
}
row ++;
}
DEMFile.close();
}
}
else cout << "Unable to open file";
}

最佳答案

关于你的第二个问题:

我会选择使用一维 vector ,然后通过 (row*ncols+col) 对其进行索引。

这至少会减少内存消耗,但也可能对速度产生重大影响。

我不记得“vector 的 vector ”是否是标准认可的习语,但如果没有对“vector 的 vector ”进行特殊处理,则存在进行过多复制和内存重新分配的风险 vector 案例。

关于c++ - 读取文本文件和使用二维 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35279475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com