c++ - STL用户定义的二进制操作

标签 c++ stl

我一直在阅读有关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()的调用。

关于c++ - STL用户定义的二进制操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60018743/

相关文章:

c++ - SDL 自身和其他窗口崩溃

c++ - 为什么我的 removestring 函数有错误

c++ - 如何返回 const std::vector<Object *const>?

c++ - setf(ios::left, ios::adjustfield) 的组合有什么作用?

c++ - 具有返回抽象类型的函数头是否合法?

c++ - Mac OS 上的 Qt - 检测停靠菜单上的点击

c++ - 在C++中制作动态队列

c++ - boost::bind 如何与 std::greater 和 std::less_equal 一起工作

c++ - 假设 STL vector 存储总是连续的是否安全?

c++ - 如何创建具有随机数据成员值的对象? C++