什么是 curry ?

如何在C++中进行计算?

请解释STL容器中的粘合剂吗?

最佳答案

简而言之,currying采用函数f(x, y)并给定固定的Y,给出新的函数g(x),其中

g(x) == f(x, Y)

在仅提供一个参数的情况下,可以调用此新函数,并将该调用传递给具有固定f参数的原始Y函数。

STL中的活页夹允许您对C++函数执行此操作。例如:
#include <functional>
#include <iostream>
#include <vector>

using namespace std;

// declare a binary function object
class adder: public binary_function<int, int, int> {
public:
    int operator()(int x, int y) const
    {
        return x + y;
    }
};

int main()
{
    // initialise some sample data
    vector<int> a, b;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    // here we declare a function object f and try it out
    adder f;
    cout << "f(2, 3) = " << f(2, 3) << endl;

    // transform() expects a function with one argument, so we use
    // bind2nd to make a new function based on f, that takes one
    // argument and adds 5 to it
    transform(a.begin(), a.end(), back_inserter(b), bind2nd(f, 5));

    // output b to see what we got
    cout << "b = [" << endl;
    for (vector<int>::iterator i = b.begin(); i != b.end(); ++i) {
        cout << "  " << *i << endl;
    }
    cout << "]" << endl;

    return 0;
}

关于c++ - 如何在C++中进行计算?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/152005/

10-10 11:19