The C++ Function using STL to Check Duplicate Elements/Character
- 时间:2020-09-17 14:37:27
- 分类:网络文摘
- 阅读:95 次

cplusplus
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.
1 2 3 4 | bool hasDuplicateCharacters(string arr) { unordered_set<char> st(begin(arr), end(arr)); return st.size() != arr.size(); } |
bool hasDuplicateCharacters(string arr) { unordered_set<char> st(begin(arr), end(arr)); return st.size() != arr.size(); }
Example:
1 2 | cout << (hasDuplicateCharacters("abcde") ? "true" : "false"); // false cout << (hasDuplicateCharacters("abcdea") ? "true" : "false"); // true |
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.
1 2 3 4 5 | template <typename T> bool hasDuplicateItems(vector<T> arr) { unordered_set<T> st(begin(arr), end(arr)); return st.size() != arr.size(); } |
template <typename T> bool hasDuplicateItems(vector<T> arr) { unordered_set<T> st(begin(arr), end(arr)); return st.size() != arr.size(); }
Example:
1 2 3 | cout << (hasDuplicateItems<int>({ 1, 2, 3, 4 }) ? "true" : "false"); // true cout << (hasDuplicateItems</int><int>({ 1, 2, 3, 4, 1 }) ? "true" : "false"); // false </int> |
cout << (hasDuplicateItems<int>({ 1, 2, 3, 4 }) ? "true" : "false"); // true cout << (hasDuplicateItems</int><int>({ 1, 2, 3, 4, 1 }) ? "true" : "false"); // false </int>
This is quite similar approach to checking the duplicates in Javascript – which is also based on the Set.
–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:诗词名句鉴赏:所谓伊人,在水一方。 诗词名句鉴赏:我思古人,实获我心。 诗词名句鉴赏:投我以木桃,报之以琼瑶。 诗词名句鉴赏:知我者,谓我心忧;不知我者,谓我何求。 齐桓公伐楚盟屈完原文及翻译 曹刿论战原文及翻译 数学题:组成只能被3整除不能被9整除的4位数 数学题:将某款服装按标价打8折出售,仍可盈利10% 数学题:把一根长30cm,底面半径是8cm的圆木平均锯成4段 数学题:甲乙两种皮鞋的原价相同,换季时
- 评论列表
-
- 添加评论