Find and print duplicate words in std::vector using STL functions using C++.

C++Server Side ProgrammingProgramming

Consider we have a list of strings. The list has some duplicate strings. We have to check which strings are occurred more than once. Suppose the string list is like [“Hello”, “Kite”, “Hello”, “C++”, “Tom”, “C++”]

Here we will use the hashing technique, so create an empty hash table, then traverse each string, and for each string, s is already present in the hash, then display the string, otherwise insert into the hash.

Example

 Live Demo

#include<iostream>
#include<vector>
#include<unordered_set>
using namespace std;
void displayDupliateStrings(vector<string> strings) {
   unordered_set<string> s;
   bool hasDuplicate = false;
   for (int i = 0; i<strings.size(); i++) {
      if (s.find(strings[i]) != s.end()) {
         cout << strings[i] << endl;
         hasDuplicate = true;
      }
      else
         s.insert(strings[i]);
   }
   if (!hasDuplicate)
      cout << "No Duplicate string has found" << endl;
}
int main() {
   vector<string>strings{"Hello", "Kite", "Hello", "C++", "Tom", "C++"};
   displayDupliateStrings(strings);
}

Output

Hello
C++
raja
Published on 29-Oct-2019 11:35:06
Advertisements