且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用STL算法查找集合中的前两个非相邻元素

更新时间:2023-02-26 17:07:53

循环的问题是您过早停止了一个元素.这有效:

The problem with your loop is that you stop one element too early. This works:

while (++i != foo.end() && *prev(i) + 1 == *i);

与第一个循环的区别是条件*prev(i) + 1 == *i)而不是*i + 1 == *next(i);您检查的范围必须相应地移动.

The difference to the first loop is the condition *prev(i) + 1 == *i) instead of *i + 1 == *next(i); the range you check has to shift accordingly.

您也可以使用std::adjacent_find:

auto i = std::adjacent_find(begin(s), end(s), [](int i, int j) { return i + 1 != j; });

if(i == s.end()) {
  std::cout << *s.rbegin() + 1 << std::endl;
} else {
  std::cout << *i + 1 << std::endl;
}

对编辑的响应:使其完全内联的一种方法是

Response to the edit: A way to make it prettily inlineable is

  std::cout << std::accumulate(begin(s), end(s), 0,
                               [](int last, int x) {
                                 return last + 1 == x ? x : last;
                               }) + 1 << '\n';

...但是效率较低,因为它在发现间隙时不会短路.造成短路的另一种方法是

...but this is less efficient because it does not short-circuit when it finds a gap. Another way that does short-circuit is

std::cout << *std::mismatch(begin     (s),
                            prev(end  (s)),
                            next(begin(s)),
                            [](int lhs, int rhs) { 
                              return lhs + 1 == rhs;
                            }).first + 1 << '\n';