for_each 给出两个(或 n 个)相邻元素
是否有一个 for_each
的标准实现来调用元素和范围内的下一个元素?
Is there a standard implementation of a for_each
that does call with the element and the next one in the range?
例如取范围{0, 1, 2, 3, 4, 5}
,我想用每个元素及其后继调用函数f
: {f(0, 1), f(1, 2), f(2, 3), f(3, 4), f(4, 5)}
注意最后一个元素是如何被遗漏的,因为它没有后继元素.
For example take the range {0, 1, 2, 3, 4, 5}
, I would like to call a function f
with each element and its successor: {f(0, 1), f(1, 2), f(2, 3), f(3, 4), f(4, 5)}
Note how the last element is left out because it has no successor.
如果将 this 推广到与元素本身一起传递的 n 后继者,那也很好.
It would also be nice if there was a generalization of this to n successors that get passed with the element itself.
到目前为止,我一直通过带有迭代器的手写循环来解决这个问题.但是,我想更多地遵循基于 for 或 std::for_each
的 C++11 范围,以避免样板代码.
Up to now I have always solved this in terms of a handwritten loop with iterators.
However, I would like to go much more along the lines of C++11 range based for or std::for_each
to avoid boiler plate code.
// today: handwritten loop
for(Range::iterator current = range.begin(); current != range.end(); ++current)
f(*current, *std::next(current));
// near future: wrapped version
for_each_pair(range.begin(), range.end(), f);
// slightly further future: generalized version
for_each_tuple<n>(range.begin(), range.end(), f);
附加问题
函数名称有待改进.对我来说 for_each_pair
/tuple
听起来应该返回范围内大小为 n 的所有子集(这本身就是我想解决的另一个问题).所以我想要一些关于更好名字的建议,比如:
Additional Question
The name of the function could be improved. To me for_each_pair
/tuple
sounds like all subsets of size n of the range should be returned (which is in itself another problem I would like to solve). So I'd like some suggestions on better names like:
for_each_adjacent<n>
临时解决方案
我已在 我自己的解决方案.com/questions/84996/adjacentelementsiteratoradaptor-for-random-access-iterators">CR.我不会在这里复制它,因为这是一个标准的解决方案,并且已经有足够多的你自己的答案.
Temporary Solution
I have posted my own solution over at CR. I won't duplicate it here because this is about a standard solution and there are already enough roll-your-own answers.
推荐答案
您实际上可以为此滥用 std::unique
或 std::adjacent_find
:谓词是用迭代器范围内的每个连续对调用,只要谓词始终返回false,它就不会修改任何内容或提前返回.
You could actually abuse std::unique
or std::adjacent_find
for this: the predicate is called with each consecutive pair in the iterator range, and as long as the predicate always returns false, it won't modify anything or return early.
不考虑那个特定的 hack,我会将它实现为迭代器适配器,而不是算法.也就是说,我将实现一个 consecutive_tuple_iterator
它将返回 N 个连续项目的所有元组.然后你可以将它用于 count_if
和 includes
之类的东西,而不仅仅是 for_each
.(不过,它不适用于大多数修改算法.)
Disregarding that particular hack, I would implement this as an iterator adapter, not an algorithm. That is, I'd implement a consecutive_tuple_iterator<N>
which would return all tuples of N consecutive items. Then you could use it for things like count_if
and includes
, not just for_each
. (It wouldn't be appropriate for most modifying algorithms, though.)
相关文章