Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find and print duplicate words in std::vector using STL functions using C++.
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
#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++
Advertisements