为何无法向stringstream对象写入string?C++单词去重代码问题
C++句子单词去重问题:原代码错误分析与修复
原代码问题根源
你遇到的words << word不生效的核心原因是:
当while (words >> w)循环遍历完整个stringstream后,流的**eofbit(结束标志)**会被置位,流进入错误状态。此时所有后续的读写操作都会被直接忽略,自然无法写入新单词。
同时原代码还有两个隐含问题:
- 每次检查时没有将读指针重置到流开头,第二次调用函数时会直接跳过读取(因为指针停在流末尾)。
- 写入单词时没有添加分隔符,会导致单词连在一起,后续读取时无法区分。
原代码修复方案
修改is_there_any函数,处理流状态和指针位置:
#include <iostream> #include <sstream> #include <string> using namespace std; bool is_there_any(string word, stringstream& words) { string w; // 将读指针移到流开头,确保每次都能读取所有已存储单词 words.seekg(0); while (words >> w) { if (word == w) return true; } // 清除流的错误状态(eof/fail标志),恢复可写能力 words.clear(); // 将写指针移到流末尾,追加新单词而非覆盖 words.seekp(0, ios::end); // 写入单词时添加空格作为分隔符 words << word << " "; return false; } int main() { string sentence, word; getline(cin, sentence); stringstream stream(sentence); stringstream words; while (stream >> word) { if (!is_there_any(word, words)) cout << word << endl; } return 0; }
更优实现方案:使用哈希集合去重
用std::unordered_set(哈希集合)替代stringstream存储已出现单词,代码更简洁且效率更高(查找/插入平均时间复杂度O(1)):
#include <iostream> #include <sstream> #include <string> #include <unordered_set> using namespace std; int main() { string sentence, word; getline(cin, sentence); stringstream stream(sentence); unordered_set<string> seen_words; while (stream >> word) { // 检查单词是否未出现过 if (seen_words.find(word) == seen_words.end()) { cout << word << endl; seen_words.insert(word); } } return 0; }
内容的提问来源于stack exchange,提问作者Nadja Popovic
相关产品推荐
相关产品推荐

