读取并存储每隔一行数据:C++代码index map为空问题排查
问题分析与修复方案
你的代码里index始终为空的核心原因很明确——tokens集合从始至终都是空的。你只读取了链接行(http)和词条行(definition),但完全没处理definition里的逗号分隔词条,直接遍历空的tokens自然不会往index里插入任何内容。另外还有两个小问题:counter++后面缺分号,文件打开失败后没有提前返回,会继续执行后续无效逻辑。
修复步骤
- 解析
definition字符串,按逗号拆分出每个词条并存入tokens - 每次处理完一组链接和词条后清空
tokens,防止下一组数据串混 - 补全
counter++的分号语法错误 - 文件打开失败时直接返回0,避免无效执行
修复后的代码
#include <sstream> #include <algorithm> int function(string filename, map<string, set<string>>& index) { int counter = 0; set<string> tokens; ifstream inStream(filename); if (!inStream.is_open()) { // 更直观的文件打开判断 return 0; } string http, definition; while (getline(inStream, http) && getline(inStream, definition)) { // 清空上一轮的tokens,避免数据残留 tokens.clear(); // 用stringstream拆分逗号分隔的词条 stringstream ss(definition); string token; while (getline(ss, token, ',')) { // 去除词条前后的空格(比如" cat"转为"cat") token.erase(token.begin(), find_if(token.begin(), token.end(), [](int ch) { return !isspace(ch); })); token.erase(find_if(token.rbegin(), token.rend(), [](int ch) { return !isspace(ch); }).base(), token.end()); if (!token.empty()) { tokens.insert(token); } } // 遍历tokens填充索引 for (const auto& v : tokens) { index[v].insert(http); counter++; } } return counter; }
关键改动说明
- 新增
stringstream拆分逻辑,解决词条提取的核心问题 - 添加空格去除逻辑,避免生成带空格的无效索引键
- 每次循环清空
tokens,保证每组链接对应正确的词条集合 - 优化文件打开失败的判断与返回逻辑,避免后续无效执行
内容的提问来源于stack exchange,提问作者B S
相关产品推荐
相关产品推荐

