在這個問題的評論is-there-a-way-to-iterate-over-at-most-n-elements-using-range-based-for-loop還有一個問題 - 這是可能有一個容器上的「索引視圖」,即有一些索引過濾出來的子範圍。一種通過索引過濾範圍的方法,只從過濾後的索引獲取min_element?
此外,我遇到了一個問題,以找出一些範圍內的最小值,並篩選出一些索引。
I.e.是有可能取代這樣的代碼,如下面性病和/或升壓算法,過濾器 - 以使其更具有可讀性和可維護:
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++ 17的建議嗎?我可以在gcc4.9中使用它嗎? – PiotrNycz
Gcc 4.9在C++ 11模式下工作,在C++ 14模式下使用clang(gcc 5.1有一些防止C++ 14模式的bug)。該提案正在跟蹤C++ 17或TS,可能與C++ 17並存。請參閱https://github.com/ericniebler/range-v3 – TemplateRex