gpt4 book ai didi

容器上滑动窗口的C++算法

转载 作者:行者123 更新时间:2023-11-30 02:48:58 31 4
gpt4 key购买 nike

我发现自己像这样编写了一个手工制作的 while 循环:

std::list<T> foo; // In my case, map, but list is simpler
auto currentPoint = std::begin(foo);
while (true) {
// Let's say the container has > 0 elements
auto nextPoint = std::next(currentPoint);
if (nextPoint == std::end(foo))
break;

// Do stuff with *currentPoint and *nextPoint
currentPoint = nextPoint;
}

按照 Sean Parent 的建议 (no raw loops),我尝试用标准算法和漂亮的 lambda 替换那个 while 循环,但我找不到合适的算法来迭代滑动窗口上的 map (一次 2 个元素)。带有 next 的简单 for_each 不起作用,因为 for_each 将对元素的引用传递给 lambda,我无法调用 next 就可以了。

std::for_each(
std::begin(skylineMap),
// Let's say the container has > 0 elements
std::prev(std::end(skylineMap)),
[&](const typename decltype(skylineMap)::value_type &currentPoint) {
auto nextPoint = ???; // next(currentPoint) wouldn't work, of course
// Do stuff with currentPoint and nextPoint
}
);

编辑:删除我想做的操作示例;这个例子似乎更令人困惑而不是澄清。

最佳答案

有几个选项可以使用预先存在的函数来执行此操作。

一种是使用 zip 类型的函数,例如带有 5 个参数和两个范围的 std::transform 重载:[c.begin() + 1, c. end())[c.begin(), c.end() - 1)。或者 for_eachboost::zip_iterator。这主要只对大小为 2 的窗口有用。

另一种方法是将 for_eachboost::counting_iterator 一起使用,这样您的回调实际上会收到一个迭代器,它可以前进以访问相邻元素。当您的回调知道它想要使用的范围大小时,这将很有用。

你也可以组合它们,在 boost::counting_iterator 上使用 boost::zip_iterator 传递一个 [begin, end) 对回调的迭代器。这很有用,因为它可以让调用者确定窗口大小。

对于一次性的,我会只编写 for 循环。

最后,如果您经常使用它,您可以将该 for 循环打包到您自己的算法函数中——它们是直接的模板。这可能比使用上述任何一种方法的复杂性低得多。

关于容器上滑动窗口的C++算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21656683/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com