首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可以在std::min中使用std::accumulate吗?

可以在std::min中使用std::accumulate吗?
EN

Stack Overflow用户
提问于 2012-07-24 15:43:59
回答 2查看 4K关注 0票数 21

我正在尝试将std::accumulatestd::min结合起来。类似这样的代码(不会编译):

代码语言:javascript
复制
vector<int> V{2,1,3};   
cout << accumulate(V.begin()+1, V.end(), V.front(), std::min<int>);

有可能吗?是否可以不为std::min编写包装器函数器

我知道我可以用lambdas做到这一点:

代码语言:javascript
复制
vector<int> V{2,1,3};   
cout << std::accumulate(
    V.begin()+1, V.end(),
    V.front(), 
    [](int a,int b){ return min(a,b);}
);

我知道有std::min_element。我不是在尝试寻找最小元素,我需要将std::accumulatestd::min (或::min)组合在我的库中,这样就可以像C++中的表达式一样进行函数编程。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-24 15:59:24

问题是有several overloads of the min function

代码语言:javascript
复制
template <class T> const T& min(const T& a, const T& b);

template <class T, class BinaryPredicate>
const T& min(const T& a, const T& b, BinaryPredicate comp);

因此,您的代码是不明确的,编译器不知道选择哪个重载。您可以通过使用中间函数指针来声明您想要的是哪一个:

代码语言:javascript
复制
#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
  std::vector<int> V{2,1,3};
  int const & (*min) (int const &, int const &) = std::min<int>;
  std::cout << std::accumulate(V.begin() + 1, V.end(), V.front(), min);
}
票数 24
EN

Stack Overflow用户

发布于 2021-09-15 16:01:24

您可以在C++20中使用std::ranges::min

代码语言:javascript
复制
#include <algorithm>
#include <iostream>
#include <vector>
#include <numeric>
#include <climits>

int main() {
    std::vector<int> v{1,2,3,47,5};
    std::cout << std::accumulate(v.begin(), v.end(), INT_MAX, std::ranges::min) << std::endl; 
    std::cout << std::accumulate(v.begin(), v.end(), INT_MIN, std::ranges::max) << std::endl; 
}

1

47

请注意,由于C++20没有这样做,因此没有std::ranges::accumulate

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11626304

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档