Implementations of count_until and accumulate_until?

后端 未结 1 1971
失恋的感觉
失恋的感觉 2021-02-14 02:17

Given an input sequence, the standard algorithms std::count and std::accumulate count the number of occurances of a specific value (or predicate matche

相关标签:
1条回答
  • 2021-02-14 03:06

    I was thinking of a combination of std::find_if with a state predicate: (Pred is normal user predicate.)

    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;
    }
    
    0 讨论(0)
提交回复
热议问题