【发布时间】:2015-09-07 16:17:56
【问题描述】:
在这个问题is-there-a-way-to-iterate-over-at-most-n-elements-using-range-based-for-loop 的 cmets 中,还有一个额外的问题 - 这是否可能在容器上具有“索引视图”,即过滤掉一些索引的子范围。
此外,我遇到了一个问题,即从过滤掉一些索引的范围中查找最小值。
即是否可以用 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;
}
}
只是这样使用:
#include <iostream>
#include <vector>
int main() {
std::vector<float> ff = {1.2,-1.2,2.3,-2.3};
auto onlyEvenIndex = [](auto i){ return (i&1) == 0;};
auto minValue = findMin(ff, onlyEvenIndex);
std::cout << *minValue << std::endl;
}
【问题讨论】:
标签: c++ templates c++11 boost c++14