gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:50:26 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com