我认为这很简单,但是当我传递这个 vector 时它返回了 true:
int arr2[] = {1, 6, 7, 89, 69, 23, 19, 100, 8, 2, 50, 3, 11, 90};
std::vector<int> vec2(arr2, arr2 + sizeof(arr2)/sizeof(int));
算法很简单:
(1) 实例化一个 map 。 (2) 对于 vector 中的每个整数, (2i) 如果它不在 map 中,添加它, (2ii) 如果它在 map 中,则返回 true。 (3)如果for结束则返回false 达到循环。
bool contains_repeats_1(const std::vector<int>& V) {
std::map<int,bool> M;
for (std::vector<int>::const_iterator it = V.begin(); it != V.end(); it++) {
if (M.count(*it) != 0) {
M.insert(std::pair<int,bool>(*it, true));
} else {
return true;
}
}
return false;
}
此外,对于如何更好地解决此问题的任何建议,我将不胜感激。我正在使用 Apple XCode,它没有包含 unordered_map 的库。
最佳答案
更简单:
std::set<int> s(vec2.begin(), vec2.end());
return s.size() < vec2.size();
这依赖于 std::set
不包含重复项这一事实。因此,如果 vector 中有任何重复项,则集合会变小。
如果您担心这会执行太多不必要的拷贝,您可以使用循环并在第一个拷贝处跳出:
std::set<int> s;
for (int i : vec2) {
if (!s.insert(i).second) return true;
}
return false;
关于c++ - 如果 vector 包含重复,则此函数应返回 true。知道为什么它不起作用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19841064/