我正在尝试将std::accumulate和std::min结合起来。类似这样的代码(不会编译):
vector<int> V{2,1,3};
cout << accumulate(V.begin()+1, V.end(), V.front(), std::min<int>);有可能吗?是否可以不为std::min编写包装器函数器
我知道我可以用lambdas做到这一点:
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::accumulate和std::min (或::min)组合在我的库中,这样就可以像C++中的表达式一样进行函数编程。
发布于 2012-07-24 15:59:24
问题是有several overloads of the min function
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);因此,您的代码是不明确的,编译器不知道选择哪个重载。您可以通过使用中间函数指针来声明您想要的是哪一个:
#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);
}发布于 2021-09-15 16:01:24
您可以在C++20中使用std::ranges::min
#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。
https://stackoverflow.com/questions/11626304
复制相似问题