coding_xeno coding_xeno - 1 year ago 54
C++ Question

How can I use function in C++ to create a sequence?

My goal is to create an immutable function (functional programming) using "accumulate" in C++. I created a dummy list that generates 1's based on the position I send, which will be 6. So the list at the start contains {1,1,1,1,1,1}. I tried using accumulate to somehow use the information on this list and make the fibonacci sequence into a new list. The result has to be {1,1,2,3,5,8}

Here is what I have.

list<int> immutableFibonacci(int position)
const size_t fixedListSize(position);
list<int> newList(position, int(1));
list<int> copyList;
list<int>::iterator it = newList.begin();

if (position <=2)
return newList; //returns {1,1} or {1}

while (position>0)
advance(it, 1);
sum = accumulate(newList.begin(),it, 0);
return copyList;

What I have so far will return copyList as {1,2,3,4,5,6}. Can someone please push me in the right direction on what to do? I tried researching quite a bit.

Answer Source

How about this:

#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <functional>

int main()
    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>{},
                                        [](const std::vector<int>& a, int b) 
                        std::vector<int> d = a;
                            auto start = d.rbegin();
                            auto first = *start;
                            auto second = *start;
                        return d;

    std::cout << "Fibo: " <<'\n';

    for( auto c : s )
        std::cout << c << "-";
    std::cout << '\n';

But I also think it is a bit too much overhead, for something that simple.

EDIT: Remember to compile that with: g++ --std=c++14 fibo.cpp -o fibo.

EDIT: If you don't want to use the lambda function look here: How can I modify this Fibonacci code in C++ to use a function instead of lambda?