泛型算法13

来源:互联网 发布:网络金融mba智库 编辑:程序博客网 时间:2024/05/22 12:52
/*author:Miracledate:2016年3月12日需求:在list容器中取代vector实现排除重复单词的程序*//*分析:1、list容器上的迭代器是双向迭代器而不是随机访问迭代器。因此,在list容器上不能使用需要随机访问迭代器,比如sort算法。2、泛型算法unique虽然可以用在list上,但是其性能会降低。过程:1、读取文本文件,存储在list容器中。2、将其重复的单词去掉,并输出输入序列中不重复的单词。*/#include<iostream>#include<list>#include<fstream>#include<algorithm>#include<string>using namespace std;void function(){string file = "Sister.txt";ifstream inFile;inFile.open(file.c_str());if (!inFile){cerr << "Can not the input file!" << endl;}list<string> words;string word;//读入需要分析的输入序列,并存放在list容器中while (inFile >> word){words.push_back(word);}//使用list中的sort算法对输入排序以便去除重复的单词words.sort();//使用list中的unique算法删除输入序列中重复的单词words.unique();//输出输入序列中不重复的单词cout << "unique words:" << endl;for (list<string>::iterator iter = words.begin(); iter != words.end(); ++iter){cout << *iter << " ";}cout << endl;}

0 0
原创粉丝点击