c++ - 是否有实现条件累加的boost或STL函数?

标签 c++ boost stl

我想实现将一个整数数组相加直到满足特定条件的代码。这是我的代码:

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 函数,但我不想把所有东西都加起来。我想把值加起来,直到它变得大于输入。数组只是一个例子,可以用 vector 或其他东西代替。

最佳答案

你可以自己写。 这是来自 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;
 }

如果你想做除加法以外的事情,他还有一个采用二元运算的方法。

关于c++ - 是否有实现条件累加的boost或STL函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23196940/

相关文章:

c++ - Qt:信号调用函数的默认参数

c++ - 防止 clang tidy 报告关于 Boost 测试 header 的警告

java - 为什么我们需要HashMap以外的数据结构

c++ - 没有 Boost.System 的 Boost.Asio

c++ - C++中的简单字典

c++ - 使用 Qt 和 Opengl 强制注销崩溃

c++ - 如何在类中初始化二维数组?

boost - boost.log 是 Boost 的正式一部分吗?

c++ - 错误是boost shared_ptr和类继承

c++ - 如何获得可调用类型的签名?