在对这个问题的评论中,有一个迭代过多的元素 - 使用基于范围的循环还有一个额外的问题 - 这可能有"索引视图"在容器上,即具有过滤掉一些索引的子范围.
另外,我遇到了一个问题,即从过滤掉一些索引的范围中找到最小值.
也就是说,可以用std和/或boost算法,过滤器替换下面的代码 - 使其更具可读性和可维护性:
template <typename Range, typename IndexPredicate>
auto findMin(const Range& range, IndexPredicate ipred)
-> boost::optional<typename Range::value_type>
{
bool found = false;
typename Range::value_type minValue{};
for (std::size_t i = 0; i < range.size(); ++i)
{
if (not ipred(i))
continue;
if (not found)
{
minValue = range[i];
found = true;
}
else if (minValue > range[i])
{
minValue = range[i];
}
}
if (found)
{
return minValue;
}
else
{
return boost::none;
} …Run Code Online (Sandbox Code Playgroud)