从C++ 11开始,在我们拥有的算法库中all_of,any_of并none_of确定谓词是否包含范围内的所有元素,任何元素或任何元素.对这些算法之一的单个调用返回1位信息,而对于特定范围和谓词,有4种可能性:
有没有简明有效的方法来查找这些信息?all_of后面的调用none_of是可能的,但是(a)不能在单遍范围上工作,并且(b)准确地对谓词进行一次必要的评估.提升是可以接受的.
Csq*_*Csq 10
如果手动检查第一个元素并在结果之间选择all_of或none_of取决于结果,则可以消除(a)(b)问题.
代码(enum从@Angew 借来):
enum class Result {
empty, all, none, some
};
template <class FwIt, class Pred>
Result examine_range(FwIt from, FwIt to, Pred pred)
{
if (from == to) return Result::empty;
if (pred(*from)) {
++from;
return all_of(from,to,pred) ? Result::all : Result::some;
} else {
++from;
return none_of(from,to,pred) ? Result::none : Result::some;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
196 次 |
| 最近记录: |