help with removing duplicate words C++
Jan 8, 2016 at 1:25am UTC
I am working on an assignment, it is to read a file, sort it and remove duplicate words and display. I got all the parts expect the removing duplicating part. Any points would be highly appreicated
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>
using namespace std;
int main()
{
vector<string> words;
string inputFileName, reply;
ifstream inputFile;
cout << "Input file name: " ;
getline(cin, inputFileName);
inputFile.open(inputFileName.c_str());
//If the file doesn't open, then display error and then ask to press enter to close
if (inputFile.is_open())
{
while (!inputFile.eof())
{
string word;
while (inputFile >> word)
{
words.push_back(word);
}
sort(words.begin(), words.end());
for (size_t i=0; i<words.size(); i++)
{
cout << words[i] << endl;
}
}
}
else
{
cout << "Unable to open input file." << endl;
cout << "Press enter to continue..." ;
getline(cin, reply);
exit(1);
}
inputFile.close();
return 0;
}
Jan 8, 2016 at 4:32am UTC
Well the way you have structured your program you can use the following method. You can define a separate function or you can code it in the main.
1 2 3 4 5 6 7 8 9 10 11 12
for (size_t i = 0; i < words.size(); i++)
{
for (size_t j = i + 1; j < words.size(); j++)
{
if (words.at(i) == words.at(j))
{
words.at(j) = words.at(words.size() - 1);
words.pop_back();
j--;
}
}
}
And I suggest that you sort the vector after the duplicate deletion is performed.
Last edited on Jan 8, 2016 at 4:33am UTC
Jan 8, 2016 at 7:11am UTC
Thank you very much that helped and the solution is surprisingly easy, but I was over thinking it
Jan 8, 2016 at 11:02am UTC
No problem
Jan 8, 2016 at 12:46pm UTC
Thanks a lot for this !!
Topic archived. No new replies allowed.