Search code examples
c++boostc++17std

Use std::all_of with boost::irange to get the loop index


I was wondering if it is possible to write an std::all_of statement with boost::irange at the same time to get the index of the item I am looping at each moment. My purpose is to refactor an expression of this kind, which looks like both of them combined:

for (auto instance : boost::irange(instances))
{
    if (not func(instance))
    {
        return false;
    }
}
return true;

Function func needs an integer instance, I cannot refactor that function parameter. I would like to rewrite as "something" like:

std::all_of(..., ..., [] () { return func(instance); })

Is it possible? Many thanks for your advice!


Solution

  • If you are already using boost, you can use boost::all_of, that has an overload taking a range and a predicate, rather than two iterators and a predicate.

    return boost::algorithm::all_of(boost::irange(instances), func);