设置没有删除重复项

Set is not removing the duplicates

本文关键字:删除 设置      更新时间:2023-10-16

我很难将单词文件放入集合中。我可以读取文件,并且单词进入集合,但该集合不会丢弃重复的单词。这是我认为正在引起问题的代码段。

using namespace std;
while(readText >> line){
     set<string> wordSet;
     wordSet.insert(line);

     for (std::set<std::string>::iterator i = wordSet.begin(); i != wordSet.end(); i++)
        {
        cout << *i << " ";
        }
  }

示例文件是 1 2 2 3 4 5 5

,输出完全相同

如注释中所述,您无法正确使用std::set。您需要移动它,而for循环在while循环之外:

using namespace std;
set<string> wordSet;
while(readText >> line) {
    wordSet.insert(line);
}
for (set<string>::iterator i = wordSet.begin(); i != wordSet.end(); i++) {
    cout << *i << " ";
}