我一直在阅读有关STL的信息,发现以下代码:
int MyFunction(int total, int value)
{
return total + value * value;
}
int main()
{
vector<int> integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int result = accumulate(integers.begin(), integers.end(), 0, MyFunction);
cout << result;
}
我的问题是:如何将参数传递给
MyFunction
。我的意思是:该函数如何分配total
和value
值?我认为答案肯定是我遗漏的简单方法,但是对此我感到很困惑。提前致谢。
最佳答案
考虑以下std::accumulate()
的可能实现:
template<class InputIt, class T, class BinaryOperation>
T accumulate(InputIt first, InputIt last, T init, BinaryOperation op)
{
for (; first != last; ++first) {
init = op(init, *first); // <-- the call
}
return init;
}
您感兴趣的部分是
op(init, *first)
。由于您要将MyFunction
作为第四个参数传递给std::accumulate()
函数模板的调用,因此:int MyFunction(int total, int value)
{
return total + value * value;
}
然后,您的情况下的
op
将被推导为int(*)(int, int)
类型(即,指向一个函数的指针,该函数需要两个int
并返回int
)。该指针指向您的函数MyFunction()
。因此,基本上,std::accumulate()
将init
和*first
分别作为第一个和第二个参数传递给对MyFunction()
的调用。
关于c++ - STL用户定义的二进制操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60018743/