我有一个有效的fibonacci函数,它从一个虚拟列表{1,1,1,1,1,1}中返回一个fibonacci数的列表。这是我的代码。
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;
}我希望传递一个函数的名称,而不是传递拉姆达表达式const list a, int b来计算。我该怎么做呢?它基本上是函数immutableFibonacci中的一个函数,但我在这样做时遇到了麻烦。
发布于 2016-09-09 12:32:33
感谢您使用我的答案:-) -> How can I use accumulate in C++ to create the Fibonacci sequence?
以下是我对您的问题的解决方案:
#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <functional>
auto fibo (std::vector<int>& a, int b) 
{
     if(a.size()<2)
     {
          a.push_back(1);
     }
     else
     {
          auto start = a.rbegin();
          auto first = *start;
          start++;
          auto second = *start;
          a.push_back(first+second);
     }
     return a;
}
int main()
{
    const std::vector<int> v{1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
    std::vector<int> s = std::accumulate(v.begin(), v.end(), 
                                     std::vector<int>{}, fibo);
    std::cout << "Fibo: " <<'\n';
    for( auto c : s )
    {
        std::cout << c << "-";
    }
    std::cout << '\n';
}记得用:g++ --std=c++14 fibo.cpp -o fibo编译它。
https://stackoverflow.com/questions/39400018
复制相似问题