使用C ++使用STL函数在std :: vector中查找并打印重复的单词。
考虑我们有一个字符串列表。列表中有一些重复的字符串。我们必须检查多次出现了哪些字符串。假设字符串列表像[“Hello”,“Kite”,“Hello”,“C++”,“Tom”,“C++”]
在这里,我们将使用哈希技术,因此创建一个空的哈希表,然后遍历每个字符串,对于每个字符串,s已经存在于哈希中,然后显示该字符串,否则将其插入哈希中。
示例
#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); }
输出结果
Hello C++