STL accumulate() function

STL accumulate() function

本文关键字:function accumulate STL      更新时间:2023-10-16

如何计算满足lower_bound(42),upper_bound从这个代码??

accumulate(values.lower_bound(42), values.upper_bound(137), 0);

accumulate不计数,它累加。当然,你可以积累1而不是元素,但这是向后的。直接的答案是std::distance,它给出了两个迭代器之间(即指定的下限和上限之间)的元素数量:

auto result = std::distance(values.lower_bound(42), values.upper_bound(137));

我认为您正在寻找的解决方案是algorithm标头中的std::count_if。如果你有一个容器cont,你可以这样使用它:

bool is_in_range(int x){
   return 42 <= x && x >= 137;
}
std::count_if(cont.begin(), cont.end(), is_in_range);