C++ 程序,用于打印文件中唯一的词语
文件是用于存储词语流的内存位置。在文件中,存在着各种各样的词语。在本程序中,我们需要从文件中找出所有唯一的词语并打印它们。
唯一的词语是指在文件中出现次数为 1 的词语。
例如,
Tutorials point is best for programming tutorials.
在此,词语教程出现了不止一次,因而它不是唯一的。其他所有的词语都是唯一的。
算法
To check for unique words in the given file. Using iterator with two variables : data and occurence. Input : File Step 1 : Read each line from the file and follow step 2 Step 2 : check for the occurence of the word in the data structure using interator.data. Step 2.1 : if data matches increase the occurrence by one corresponding to the data. Step 2.2 : if data does not match add new value and set its occurence to one. Step 3: Iterate over the date structure. And check for occurence value of each value. Step 3.1 : If the occerence is equals to 1 then prints the data corresponding it else do nothing.
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
char filename[] = "test.txt";
ofstream fs("test.txt", ios::trunc);
fs << "tutorials point is best for programming tutorials";
fs.close();
fstream fs("test.txt");
map<string, int> mp;
string word;
while (fs >> word){
if (!mp.count(word))
mp.insert(make_pair(word, 1));
else
mp[word]++;
}
fs.close();
for (map<string, int> :: iterator p = mp.begin();
p != mp.end(); p++){
if (p->second == 1)
cout << p->first << endl;
}
return 0;
}输出
best for is point Programming
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP