是否有一个实现条件累积的boost或stl函数?

时间:2014-04-21 11:55:38

标签: c++ boost stl

我想实现代码,在它满足特定条件之前添加一组int。这是我的代码:

int x [5];

int GetIndex (int val)
{
    int i; 
    int xtotal=0; 

    for (i=0; i < 5; ++i) {
        if (xtotal > val) 
            break;
        xtotal += x [i];
    }


    return i;    
}

我正在使用c ++ 03。我遇到了stl accumulate函数,但我不想把所有东西都加起来。我想添加值,直到它变得大于输入。数组只是一个例子,可以用矢量或其他东西代替。

2 个答案:

答案 0 :(得分:1)

你可以写自己的。 这是来自http://www.richelbilderbeek.nl/CppAccumulate_if.htm

的那个
template
   <
   typename InputIterator,
   typename ElementType,
   typename Predicate
   >
 const ElementType accumulate_if(
   InputIterator first,
   const InputIterator last,
   ElementType init,
   const Predicate predicate)
 {
   for (; first != last; ++first)
     if (predicate(*first)) init += *first;
   return init;
 }

他还有一个采取二元操作的方法,以防你想做除了加法之外的其他事情。

答案 1 :(得分:1)

您可以使用类似(c ++ 03)的内容:

template<class InputIt, class T>
std::pair<InputIt, T>
accumulate_until(InputIt begin, InputIt end, T value, T thresold_value)
{
    for (InputIt it = begin; it != end; ++it) {
        value += *it;
        if (thresold_value < value) {
            return std::make_pair(it, value);
        }
    }
    return std::make_pair(end, value);
}

或更通用的解决方案(c ++ 03):

namespace detail
{
    template <typename T, typename Pred>
    class InternalPredicate
    {
    public:
        InternalPredicate(T& value, Pred& pred) : value(value), pred(pred) {}

        bool operator () (const T& t) {
            value += t;
            return pred(value);
        }
    private:
        T& value;
        Pred& pred;
    };
}

template<class InputIt, class T, class Pred>
std::pair<InputIt, T>
accumulate_until(InputIt begin, InputIt end, T value, Pred pred)
{
    InputIt it = std::find_if(begin, end, detail::InternalPredicate<T, Pred>(value, pred));
    return std::make_pair(it, value);
}

或在C ++ 11中:

template<class InputIt, class T, class Pred>
std::pair<InputIt, value>
accumulate_until(InputIt begin, InputIt end, T value, Pred pred)
{
    auto internal_pred = [&value, &pred] (const T& t) {
        value += t;
        return pred(value);
    };
    InputIt it = std::find_if(begin, end, internal_pred);
    return std::make_pair(it, value);
}