从文件中读取整数并将其存储在二维矢量中
Reading integers from a file and store it in a 2D vector
从文件中读取并保存回2D矢量时遇到问题。这是写在文件上的函数:
void create_input (int num_frames, int height, int width)
{
ofstream GridFlow;
GridFlow.open ("GridDB");
for (int i = 0; i < num_frames; i++)
{
for (int j = 0; j < height; j++)
{
for (int k = 0; k < width; k++)
{
GridFlow << setw(5);
GridFlow << rand() % 256 << endl;
}
}
}
GridFlow.close();
}
这只是为每行(高度*宽度*num_frames)写入一个随机数的次数。像这样:
3
74
160
78
15
30
127
64
178
15
107
我想做的是从文件中读回,并将文件的不同块(宽度*高度)保存在不同的帧中。我试过这样做,但程序块没有任何错误:
vector<Frame> movie;
movie.resize(num_frames);
for (int i = 0; i < num_frames; i++)
{
Frame frame;
int offset = i*width*height*6;
vector<vector<int>>tmp_grid(height, vector<int>(width, 0));
ifstream GridFlow;
GridFlow.open ("GridDB");
GridFlow.seekg(offset, GridFlow.beg);
for (int h = 0; h < height; h++)
{
for (int g = 0; g < width; g++)
{
int value;
GridFlow >> value;
tmp_grid[h][g] = value;
}
}
frame.grid = tmp_grid;
movie[i] = frame;
}
我使用了一个偏移量,每次乘以6(字节数*行)开始读取,结构Frame只是一个2D向量来存储值。我必须对偏移量进行处理,因为下一步将进行多线程处理,每个知道帧数的线程都应该计算正确的偏移量,以开始读取和存储。
假设文件如下:
1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
以下是一种方法,说明如何将文件读取为矢量并将其输出到另一个文件:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
int main()
{
using vvint = std::vector<std::vector<int>>;
std::ifstream file{ "file.txt" };
vvint vec;
std::string line;
while (std::getline(file, line)) {
std::stringstream ss(line);
std::string str_num;
std::vector<int> temp;
while (std::getline(ss, str_num, ',')) {
temp.emplace_back(std::stoi(str_num));
}
vec.emplace_back(temp);
}
std::ofstream out_file{ "output.txt" };
for (const auto& i : vec) {
for (const auto& j : i) {
out_file << j << ", ";
}
out_file << 'n';
}
}
相关文章:
- 带结构的二维矢量:如何存储元素
- 在二维向量或数组中可以存储的最大元素数是多少?
- 如何在二维数组中存储值?
- 如何将 numpy 二维数组作为一种可以用C++读取的二进制格式存储在磁盘上
- 如何在C++中将.csv文件的元素存储到二维向量中?
- 我无法将 Excel 中的输入字符串存储为二维字符串
- C++ ->尝试逐字阅读一行文本。如何使指针等效于用于存储输入的当前二维数组
- 使用什么数据结构来存储基于游戏对象的二维单元地图?
- 如何使用二维数组来计算和存储来自其他数组的值的频率
- 我如何在二维向量中存储一些数组
- 存储二维数组指针的方法是什么
- visual 将文件中的数据存储到C++中的二维数组中
- 从文件中读取整数并将其存储在二维矢量中
- 如何在二维数组中存储数据并使用2个循环显示二维
- 什么是快速矩阵或二维数组,用于在C++中存储邻接矩阵
- 如何在大型二维数组中存储数据
- 如何从文本文件中读取矩阵并将其存储到二维数组中
- 如何将字符变量存储为二维字符变量
- 存储具有不同列大小的动态分配的二维数组
- 如何在c++中按列主顺序存储二维数组中的值