大佬教程收集整理的这篇文章主要介绍了c – count_until和accumulate_until的实现?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
如果想知道输入序列是否包含精确/至少/最多n个出现/匹配,或者累加到一个/至少/至多n个的总和,该怎么办?强力的方法是将std :: count或std :: accumulate的结果与目标n进行比较,但是当计数或累积超过目标已经在输入序列的一半时,会错过早期退出机会.
例如,做一个count_until as
template<class InputIt,class T,class Pred> auto count_until(InputIt first,InputIt last,const T& value,Pred pred) { auto res = 0; for (; first != last; ++first) if (*first == value && pred(++res)) break; // early exit if preDicate is satisfied return std::make_pair(first,res); // iterator and value to allow conTinuation }
并且可以通过使用合适的谓词和与返回的计数进行比较来测试平等/至少/最多.
问题:
>是否可以使用现有的标准算法来组合count_until(和accumulate_until类似),可能与合适的Boost.Iterator结合使用?
>特别是,我在一个accumulate_iterator上想到一个find_if,其中谓词将从迭代器中提取计数或总和.
>或者做count_until和accumulate_until保证在标准库的未来版本中包含为独立原语?
template<class InputIt,class Pred> typename iterator_Traits<InputIterator>::difference_type count_until(InputIt begin,InputIt end,Pred pred) { typename iterator_Traits<InputIterator>::difference_type count = 0; auto internal_pred = [&count,&value,&pred](decltype(*begin) elem) { return elem == value && pred(++count); }; std::find_if(begin,end,internal_pred); return count; } template<class InputIt,class Pred> T accumulate_until(InputIt begin,T value,Pred pred) { auto internal_pred = [&value,&pred] (const T& t) { value += t; return pred(value); }; std::find_if(begin,internal_pred); return value; }
以上是大佬教程为你收集整理的c – count_until和accumulate_until的实现?全部内容,希望文章能够帮你解决c – count_until和accumulate_until的实现?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。