Let’s say we want to implement a C++ function based on STL containers to check if a given string contains duplicate characters, or a given vector/array contains duplicate elements. Luckily we can use the unordered set (or set which maintains order), that we can construct a set based on the vector/array/string, then we just need to compare the sizes of both set and the original container – if they are equal, it means all unique elements or duplicates otherwise.
bool hasDuplicateCharacters(string arr) {
unordered_set<char> st(begin(arr), end(arr));
return st.size() != arr.size();
}
Example:
cout << (hasDuplicateCharacters("abcde") ? "true" : "false"); // false
cout << (hasDuplicateCharacters("abcdea") ? "true" : "false"); // true
We can use the C++ generic that allows us to pass in most data types – using the templates.
template <typename T>
bool hasDuplicateItems(vector<T> arr) {
unordered_set<T> st(begin(arr), end(arr));
return st.size() != arr.size();
}
Example:
cout << (hasDuplicateItems({ 1, 2, 3, 4 }) ? "true" : "false"); // true
cout << (hasDuplicateItems ({ 1, 2, 3, 4, 1 }) ? "true" : "false"); // false
This is quite similar approach to checking the duplicates in Javascript – which is also based on the Set.
–EOF (The Ultimate Computing & Technology Blog) —
294 wordsLast Post: How to Find Positive Integer Solution for a Given Equation using Bruteforce, Two Pointer or Binary Search Algorithms?
Next Post: C++ Coding Reference: sort() and stable_sort()
