user2799788
user2799788

Reputation: 103

Remove duplicate strings in string vector

I have the code, listed below, which I am trying to get to remove any duplicate football team names from a string vector. However, it is only working sometimes, it will remove duplicate names for some of the teams; but then for others there will be multiple occurrences of the same team name in the final array.

For example it would print:

aresnal
wigan
villa
liverpool
villa

Notice there are two 'villa' names, could anyone give me a suggestion? The 'finalLeague' is the array which is storing all of the names, and is the array which needs the duplicates removing out of.

  for (int i = 0;i < finalLeague.size();i++)
  {       
      string temp = finalLeague[i];
      int h = i + 1;
      for (int j = i+1;j < finalLeague.size();j++)
      {
          if (finalLeague[j] == finalLeague[i])
          {               
              finalLeague.erase(finalLeague.begin()+j);     
          }     
      }
  }

Upvotes: 2

Views: 5086

Answers (3)

juanchopanza
juanchopanza

Reputation: 227418

Sure, you can use a combination of std::sort, std::unique and std::vector::erase:

std::sort(finalLeague.begin(), finalLeague.end());
auto it = std::unique(finalLeague.begin(), finalLeague.end());
finalLeague.erase(it, finalLeague.end());

Alternatively, use a container that does not accept duplicates in the first place:

std::set<std::string> finalLeague;           // BST, C++03 and C++11
std::unordered_set<std::string> finalLeague; // hash table, C++11

Upvotes: 7

Jepessen
Jepessen

Reputation: 12415

you should use std::unique

std::vector<std::string> vec;
// filling vector
// ....

std::vector<std::string>::iterator it;
it = std::unique (vec.begin(), vec.end());
vec.resize(std::distance(vec.begin(),it)); 

@edit: as @Gorpik said, vector must be sorted before use std::unique, otherwise only equal consecutive elements will be deleted.

Upvotes: 0

Ranveer
Ranveer

Reputation: 6863

This can also be done using a hashmap. Using #include <unordered_map> will let you use it. Note that you might have to use C++ 11 for it. Read about unordered maps here.

All you need to do is check whether the string has occurred before or not and keep pushing unique strings into a new vector.

USP of this method is that it needs minimal amount of code. Just one loop would do the trick.

Upvotes: 0

Related Questions