我想设计一种方法来检查 std::set 中的数字序列例如,我有
set [1,3,4]
我可以找出集合中缺少 2 号,我能做的是在集合上做一个循环,并检查(current number - previous number) == 1
,如果是,循环将继续下一个直到结束。如果没有,则找到丢失的号码。
但这对我的方法似乎不好,所以我想知道是否有现有的 std lib 或 boost 可以用于这种比较?
非常感谢!
您可以用 STL 算法 (C++11) 替换 for 循环:
auto it = begin(your_set);
while (it != end(your_set)) {
it = std::adjacent_find(it,
end(your_set),
[](int a, int b){ return (b - a) != 1; });
if (it != end(your_set)) {
std::cout << "Found gap at: " << *it << std::endl;
++it;
}
}
这将找到你的集合中的所有空白。
Lambda 函数、auto
关键字和独立的开始/结束是 C++11 中的新特性。
你也可以通过递归来做到这一点。建议的解决方案是用 Java 编写的,但应该很容易移植到 C++。
public boolean isSequenceValid(int[] sequence) {
if (sequence.length == 0) return true;
return isNumberValid(sequence, 0, sequence[0]);
}
private boolean isNumberValid(int[] sequence, int index, int expectedValue) {
if (index >= sequence.length) return true;
if (sequence[index] != expectedValue) return false;
return isNumberValid(sequence, index+1, expectedValue+1);
}