C++ program to print unique words in a file
Last Updated :
07 Aug, 2022
Write a function that takes a file name as argument and prints all unique words in it. We strongly recommend you to minimize your browser and try this yourself first The idea is to use map in STL to keep track of words already occurred.
C
#include <bits/stdc++.h>
using namespace std;
void printUniquedWords( char filename[])
{
fstream fs(filename);
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;
}
}
int main()
{
char filename[] = "test.txt" ;
ofstream fs(filename, ios::trunc);
fs << "geeks for geeks quiz code geeks practice for qa" ;
fs.close();
printUniquedWords(filename);
return 0;
}
|
Output:
code
practice
qa
quiz
Time complexity: O(nlogn) where n is no of words in given file
Auxiliary Space: O(n)
Thanks to Utkarsh for suggesting above code.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...