使用 std::all_of 和 boost::irange 获取循环索引

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

提问人:Victor 提问时间:3/15/2021 更新时间:3/15/2021 访问量:214

问:

我想知道是否可以同时编写一个语句来获取我每时每刻循环的项目的索引。我的目的是重构这种表达式,它看起来像是两者的组合:std::all_ofboost::irange

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

函数需要一个整数,我无法重构该函数参数。我想重写为“东西”,如下所示:funcinstance

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

可能吗?非常感谢您的建议!

C++ 提升 C++17 标准

评论

1赞 rafix07 3/15/2021
还需要一行,其中 result of 存储为 : ,则 的调用将如 所示。Coliru,演示irangeauto r = boost::irange(instances);all_ofstd::all_of(std::begin(r), std::end(r), [](int instance){ return func(instance); });
0赞 Victor 3/15/2021
@rafix07 这个解决方案太棒了!如果您将其发布为解决方案,我会将其设置为解决方案。非常感谢!

答:

1赞 Caleth 3/15/2021 #1

如果您已经在使用 boost,则可以使用 boost::all_of,它有一个重载,采用一个范围和一个谓词,而不是两个迭代器和一个谓词。

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