STL 用户定义的二进制操作

STL user defined binary operations

本文关键字:二进制 操作 定义 用户 STL      更新时间:2023-10-16

我一直在阅读有关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。我的意思是:函数如何分配totalvalue值? 我想答案一定是我错过的简单东西,但我对此真的很困惑。提前谢谢。

考虑以下可能的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()的第一个和第二个参数传递。

看看 cpp偏好:

https://en.cppreference.com/w/cpp/algorithm/accumulate

template<class InputIt, class T, class BinaryOperation>
constexpr // since C++20
T accumulate(InputIt first, InputIt last, T init, 
BinaryOperation op)
{
for (; first != last; ++first) {
init = op(std::move(init), *first); // std::move since C++20
}
return init;
}

应该明确发生了什么

std::accumulate总是传递固定数量的参数,因此它知道如何调用你的函数,因为如果它采用不同数量的参数,代码将无法编译。 至于如何实现,cppreference有一些很好的例子 - https://en.cppreference.com/w/cpp/algorithm/accumulate - 例如:

template<class InputIt, class T>
constexpr // since C++20
T accumulate(InputIt first, InputIt last, T 
init)
{
for (; first != last; ++first) {
init = std::move(init) + *first; // std::move since C++20
}
return init;
}