繁体   English   中英

检查数字C ++的顺序

[英]check order of numbers C++

我想设计一种检查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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM