我有一个相当大的二维矢量字符串我想写一个CSV文件,但我的代码在我写的时候崩溃了。有什么建议吗?
if (outfile.is_open()) {
for (int i = 0; i < width.size() - 1; i++) {
for (int j = 0; j < rows.size() - 1; j++) {
outfile << cells[i][j] << ",";
}
outfile << endl;
}
} else cout << "Unable to write.";
宽度,行和单元格的声明:
//Declare stuff
vector<string> rows, cols, width;
vector< vector<string> > cells;
string line;
//Open input file
std::ifstream infile("99-110.csv", ios_base::in);
std::ofstream outfile("99-110_corr.csv", ios_base::out);
//Create vector with each row as an index
while (getline(infile, line)) {
rows.push_back(line);
width = split(rows[0], ",");
}
//Split each vector index into a 2D vector
for (int i = 0; i < rows.size(); i++) {
cols = split(rows[i], ",");
cells.push_back(cols);
}
事实证明我将rows.size()和width.size()混淆了。我交换了它们,现在一切似乎都适用于小文件,但是对于大于500 MB的文件,我的脚本在抛出'std :: bad_alloc'的实例后,在终止时调用崩溃。它似乎在for循环期间崩溃,我将每个向量索引分成2D向量(上面提供的最后一个循环)。向量“单元格”的最大大小为357,913,941,但我计算出向量的实际大小为97,780,085。
答案 0 :(得分:1)
为什么需要rows, cols, width
? cells
包含我想要的所有信息,所以:
for (int i = 0; i < cells.size(); i++) { // start from i=1 to skip header
for (int j = 0; j < cells[i].size(); j++) {
您可以阅读cells
,例如:
while (getline(infile, line))
cells.push_back(split(line, ","));