Tem*_*Rex 10 c++ algorithm boost stl c++11
给定输入序列,标准算法std::count并std::accumulate计算特定值(或谓词匹配std::count_if)的出现次数以及给定关联操作的累积(求和,乘积,布尔值或/和,最小值/最大值,字符串串联等) .), 分别.
如果想知道输入序列是否包含完全/至少/最多出现n/匹配,或者累积到精确/至少/最多的总和,该n怎么办?蛮力方式是比较目标的结果std::count或std::accumulate目标n,但是当计数或累积超过输入序列中途的目标时,这将错过早期退出机会.
人们可以例如使count_until作为
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
}
Run Code Online (Sandbox Code Playgroud)
通过使用合适的谓词并与返回的计数进行比较,可以从中测试相等性/至少/最多.
问题:
count_until(并且类似地accumulate_until),可能与合适的Boost.Iterator结合使用?find_if一个多accumulate_iterator,其中谓词将提取的迭代器计数或总和.count_until并accumulate_until保证在未来版本的标准库中作为独立原语包含在内?编辑:我认为最有用的方法是返回一个std::pair迭代器和一个首次满足谓词的点的计数.这使用户能够继续迭代.
我在考虑std :: find_if与状态谓词的组合:( Pred是普通用户谓词.)
template<class InputIt, class T, class Pred>
typename iterator_traits<InputIterator>::difference_type
count_until(InputIt begin, InputIt end, const T& value, 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 T, class Pred>
T accumulate_until(InputIt begin, InputIt end, T value, Pred pred)
{
auto internal_pred = [&value, &pred] (const T& t) {
value += t;
return pred(value);
};
std::find_if(begin, end, internal_pred);
return value;
}
Run Code Online (Sandbox Code Playgroud)