c++ - 如何修改此代码以使用函数而不是 lambda?

标签 c++

我有一个有效的斐波那契函数,它从虚拟列表 {1,1,1,1,1,1} 返回斐波那契数列表。这是我的代码。

list<int> immutableFibonacci(int position)
{
list<int> oldList(position, int(1));

list<int> newList = accumulate(oldList.begin(), oldList.end(), list<int>{},
    [](const list<int> a, int b)
{
    list<int> d = a;

    if (a.size()<2)
    {
        d.push_back(1);
    }
    else
    {
        auto start = d.rbegin();
        auto first = *start;
        start++;
        auto second = *start;
        d.push_back(first + second);
    }
    return d;
});
    return newList;
}

我不想传递 lambda 表达式 [](const list a, int b) 进行计算,而是传递函数的名称。我该怎么做呢?它基本上是函数 immutableFibonacci 中的一个函数,但我在执行此操作时遇到了麻烦。

最佳答案

而不是:

list<int> newList = accumulate(oldList.begin(), oldList.end(), list<int>{},
    [](const list<int> a, int b)
{
    list<int> d = a;

    if (a.size()<2)
    {
        d.push_back(1);
    }
    else
    {
        auto start = d.rbegin();
        auto first = *start;
        start++;
        auto second = *start;
        d.push_back(first + second);
    }
    return d;
});

上面,并传递一个实际的函数,就像这样。您需要函数指针:

list<int> newList = accumulate(oldList.begin(), oldList.end(), list<int>{},
    funcname);

//Below is the function    

list<int> funcname(list<int> a, int b) {
    list<int> d = a;

    if (a.size()<2)
    {
        d.push_back(1);
    }
    else
    {
        auto start = d.rbegin();
        auto first = *start;
        start++;
        auto second = *start;
        d.push_back(first + second);
    }
    return d;
}

对于自定义比较器,您可以传递函数指针或 lambda,对于您的示例,您使用了 lambda。

关于c++ - 如何修改此代码以使用函数而不是 lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39400018/

相关文章:

c++ - 使用 MacPorts 在 OSX 10.6 上安装 OpenCV

c++ - 使用模板元编程 [C++11] 对整数列表进行操作

c++ - C++中用于实时语音转换器系统的库?

C++的双冒号用在类名后面而不是命名空间

c++ - gcc Boost 模板结果为 "defined in discarded section"

c++ - cocos2dx 当我将 setPhysicsBody 设置为 sprite 时,sprite 消失了

C++推前迭代

c++ - 模板错误

C++ 转换运算符

c++ - "Mixing a dll boost library with a static runtime is a really bad idea..."