coding_xeno - 1 year ago 80
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)
{
sum = accumulate(newList.begin(),it, 0);
copyList.push_back(sum);
position--;
}
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.

``````#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;
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;
});

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download