有效地将文件读取到2d数组
Reading file to the 2d array efficently
我有两个大文件一个是int
,另一个是float
。我想将它们存储在2d vector
中。
读取这样的数据最快的方法是什么?
注意:每行元素的个数在整个文档中是唯一的。
我做了什么?
std::string temp;
std::ifstream infile(Path);
int i=0;
std::vector<std::vector<float> data(100, std::vector<float>(1000));
while (std::getline(infile, temp))
{
std::istringstream buffer(temp);
int j = 0;
while (!buffer.eof())
{
float temp2;
buffer >> temp2;
if (buffer.fail())
{
throw "Undefined variable in the input file!";
}
data.at(i).at(j) = temp2;
j++;
}
i++;
}
这个代码非常慢!
如果元素(和行)的数量是唯一的,则不能使用预大小的向量和索引。
它不仅会在元素多于预期时中断,而且所有未替换的元素都将为零(或空)。
相反,从空向量开始并使用push_back
。
为了避免重新分配向量,您可以先使用reserve
。
像这样:
std::string line;
std::ifstream infile(Path);
std::vector<std::vector<float>> data;
data.reserve(100); // Assuming no more than 100 lines
while (std::getline(infile, line))
{
data.emplace_back();
std::vector<float>& row = data.back();
row.reserve(1000); // Assuming 1000 elements will do
std::istringstream buffer(line);
float element = 0;
while (buffer >> element)
{
row.push_back(element);
}
}
如果您想要尽可能快地阅读,请不要使用文本格式的数据。
几点提示,
-
通过添加:
std::ios::sync_with_stdio(false);
在你的代码的顶部。
-
重用std::istringstream, put:
std::istringstream buffer(temp);
而不是:
data.at(i).at(j) = temp2;
在循环之外,使用buffer.clear();
使用:
data[i][j] = temp2;
这个版本不检查边界,所以它稍微快一些。
相关文章:
- 2D数组来自文本输入,中间有空格
- 如何使用用户输入在C++中正确填充2D数组
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在C++函数中声明静态 2D 数组?
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 获取 2D 数组 c++ 中的所有数字对
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 如何在构造函数中使用初始值设定项设置具有相同值的 2d 数组?
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 如何创建一个所有行大小不同的 2D 数组,并且用户将指定每行将有多少个元素?
- 使用指针算法修改函数中的 2D 数组
- 在C++中初始化和打印 2D 数组
- 有没有办法使用输入的维度初始化 2d 数组中的所有项目而不循环C++?
- C++ 2D 数组写入多个位置
- 检测到堆损坏:在正常块 c++ 动态 2D 数组之后
- 如何从initializer_list初始化 2D 数组
- 交换函数不是在 C++ 中交换 2D 数组的元素