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