如何使用C ++中的函数创建序列? [英] How can I use function in C++ to create a sequence?

查看:103
本文介绍了如何使用C ++中的函数创建序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在C ++中使用accumulate创建一个不可变的函数(函数式编程)。我创建了一个虚拟列表,基于我发送的位置生成1,这将是6.所以开始列表包含{1,1,1,1,1,1}。我试图使用积累以某种方式使用此列表上的信息,并将fibonacci序列成一个新的列表。结果必须是{1,1,2,3,5,8}

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}

这里是我有。

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); 
    copyList.push_back(sum);
    position--;
}
    return copyList;
}

到目前为止,我将返回copyList为{1,2,3, 4,5,6}。有人可以推我在正确的方向做什么?我试着研究了很多。

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.

编辑:记住编译:g ++ --std = c ++ 14 fibo.cpp -o fibo。

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

编辑:如果你不想使用lambda函数,请看这里:

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?

这篇关于如何使用C ++中的函数创建序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆