Removing the duplicates of a word sorting program

I was asked to make a program that sorts the words of a text (ascending) and remove the duplicate words. I manage to sort the words but can't remove the duplicates. When I try to add the codes to remove the duplicate words, my program become terminated, can anyone help me ?
Here's my working code before trying to add the code to remove the duplicates :
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
// load a string vector with words from a whitespace 
// separated text file and sort the words

#include <string>
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main() 
{
  vector<string> sV;
  ifstream in("paragraph.txt");
  string word;
  
  // separates words in file at a whitespace
  // and loads a string vector
  while(in >> word)
    sV.push_back(word);
     
  cout << "Unsorted words:" << endl;
  for(int i = 0; i < sV.size(); i++)
    cout << sV[i] << endl;
  
  cout << "---------------" << endl;
    
  cout << "Sorted words:" << endl;
  sort( sV.begin(), sV.end() );
  for(int i = 0; i < sV.size(); i++)
    cout << sV[i] << endl;  
  
  cin.get();
  return 0;
}

Here's the terminated code after trying to remove the duplicate words:
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
// load a string vector with words from a whitespace
// separated text file and sort the words

#include <string>
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
  vector<string> sV;
  ifstream in("paragraph.txt");
  string word;

  // separates words in file at a whitespace
  // and loads a string vector
  while(in >> word)
    sV.push_back(word);

  cout << "Unsorted words:" << endl;
  for(int i = 0; i < sV.size(); i++)
    cout << sV[i] << endl;

  cout << "---------------" << endl;

  cout << "Sorted words:" << endl;
  sort( sV.begin(), sV.end() );

  int i;
  int j;
  for(int i = 0; i < sV.size(); i++)
  {
     for(int j=0; j<sV.size(); j++)
     {
          if(sV[i].compare(sV[j]) == 0)
          {
               sV.erase(sV.begin() + j);
          }
     }
}
    cout << sV[j] << endl;

  cin.get();
  return 0;
}

I'm very new in programming, so I don't understand actually understand the problem, can someone help me fix it ?
Last edited on
I notice you have used C++ STL so to remove duplicates can use the algorithm classes.

Approach 1 (manipulate the existing vector)
Step 1
http://www.cplusplus.com/reference/algorithm/remove/

Step 2
http://www.cplusplus.com/reference/stl/vector/erase/

Approach 2 (write the no-duplicates into another container)
Step 1
http://www.cplusplus.com/reference/algorithm/remove_copy/
To remove duplicates, you only need to compare a word with the next one, not the entire collection.
Topic archived. No new replies allowed.