从.txt文件读取未知大小整数二维数组的最高效方法是什么?
不定长矩阵高效读取实现方案
核心思路
放弃两次遍历文件的方案,仅做1次IO读取,用动态扩容结构自动存储内容,避免手动预计算行列数的冗余操作。
C++ 最优实现(推荐)
直接用STL的vector容器自动管理内存,无需手动处理扩容逻辑,代码简洁且性能达标:
#include <iostream> #include <fstream> #include <vector> #include <string> #include <sstream> #include <cctype> using namespace std; int main() { ifstream fin("read.txt"); vector<vector<int>> matrix; string line; while (getline(fin, line)) { // 过滤非矩阵行:判断行内是否包含矩阵行的特征字符分号 if (line.find(';') == string::npos) continue; vector<int> row; stringstream ss(line); char sep; // 接收逗号、分号、空格等分隔符 int num; while (ss >> num) { row.push_back(num); ss >> sep; // 跳过后面的逗号/分号/空格 } matrix.push_back(row); } // 后续使用:行数为matrix.size(),列数为matrix[0].size() fin.close(); return 0; }
方案优势
- 仅1次文件遍历,IO耗时减半
- 自动适配任意行列数的矩阵,无需提前统计尺寸
- 自动处理分隔符,兼容空格、逗号、行尾分号的格式要求
- 无需手动管理内存,避免数组越界、内容丢失等问题
C 语言兼容实现
如果只能用C语言,改用realloc替代malloc即可解决新增行时清空原有内容的问题,realloc会自动拷贝原有内存块的内容到新的扩容块中:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int main() { FILE* fp = fopen("read.txt", "r"); int** matrix = NULL; int rows = 0, cols = 0; char line[1024]; while (fgets(line, sizeof(line), fp)) { // 过滤非矩阵行 if (!strchr(line, ';')) continue; // 扩容行数组 matrix = realloc(matrix, (rows + 1) * sizeof(int*)); int* row = NULL; int cur_col = 0; char* p = line; while (*p) { // 跳过非数字字符 while (*p && !isdigit(*p) && *p != '-') p++; if (!*p) break; // 读取整数 int num = strtol(p, &p, 10); row = realloc(row, (cur_col + 1) * sizeof(int)); row[cur_col++] = num; } matrix[rows++] = row; cols = cur_col; } // 使用完后手动释放内存 for (int i = 0; i < rows; i++) free(matrix[i]); free(matrix); fclose(fp); return 0; }
注意事项
- 你之前遇到的新增行清空原有内容的问题,是因为用
malloc每次申请了全新内存块、没有拷贝旧数据导致的,改用realloc即可解决 - 单次IO遍历的效率远高于两次遍历,尤其是大文件场景下性能差异非常明显
内容的提问来源于stack exchange,提问作者RigorousStudent
相关产品推荐
相关产品推荐

