提问人:Victor 提问时间:3/15/2021 更新时间:3/15/2021 访问量:214
使用 std::all_of 和 boost::irange 获取循环索引
Use std::all_of with boost::irange to get the loop index
问:
我想知道是否可以同时编写一个语句来获取我每时每刻循环的项目的索引。我的目的是重构这种表达式,它看起来像是两者的组合:std::all_of
boost::irange
for (auto instance : boost::irange(instances))
{
if (not func(instance))
{
return false;
}
}
return true;
函数需要一个整数,我无法重构该函数参数。我想重写为“东西”,如下所示:func
instance
std::all_of(..., ..., [] () { return func(instance); })
可能吗?非常感谢您的建议!
答:
1赞
Caleth
3/15/2021
#1
如果您已经在使用 boost,则可以使用 boost::all_of
,它有一个重载,采用一个范围和一个谓词,而不是两个迭代器和一个谓词。
return boost::algorithm::all_of(boost::irange(instances), func);
评论
irange
auto r = boost::irange(instances);
all_of
std::all_of(std::begin(r), std::end(r), [](int instance){ return func(instance); });