递归:使用参数中传递的值

时间:2012-12-11 05:02:07

标签: c++ recursion

我得到了这行代码,弹出数组的int将其保存到int element,然后将其从数组中删除。然后在return语句中返回CountCriticalVotes(rest, blockIndex + element);它将它广告到blockIndex变量,如果它在数组为空之前达到10则返回1.但我的问题是这个,我不希望它加起来参数中数组中的所有值,但只添加一个然后将参数值恢复为原始状态,然后添加一个新的,还原等...我该怎么做?

int NumCriticalVotes :: CountCriticalVotes(Vector<int> & blocks, int blockIndex)
{
    if (blockIndex >= 10)
    {
        return 1;
    }
    if (blocks.isEmpty())
    {
        return 0;


    } else {

        int element = blocks.get(0);
        Vector<int> rest = blocks;
        rest.remove(0);
        return  CountCriticalVotes(rest, blockIndex + element);

4 个答案:

答案 0 :(得分:1)

您可以修改代码以便计算关键投票,然后将元素重新推送到列表的前面。它看起来像这样:

blocks.remove(0);
int votes = CountCriticalVotes(blocks, blockIndex + element);
blocks.push_front(element);
return votes;

这并不能完全符合您的要求,因为它只在初始函数调用完成后才会被恢复,但最终结果是相同的。

答案 1 :(得分:1)

进行递归调用时,可以传递一个临时向量,该向量由索引1到结尾的所有元素组成。您的原始矢量将保持不变。这确实创建了许多临时向量,但原始代码也是如此。这是基于您的示例的快速代码示例。

#include <iostream>
#include <vector>
using namespace std;

bool CountCriticalVotes(vector<int>& blocks, int sum = 0) {
    if (sum >= 10) {
        return true;
    } else if(blocks.empty()) {
        return false;
    } else {
        vector<int> temp(blocks.begin() + 1, blocks.end());
        return CountCriticalVotes(temp, sum + blocks.at(0));
    }
}

int main() {
    vector<int> foo = { 2, 3, 4, 5, 6};
    vector<int> bar = { 2, 3 };
    cout << boolalpha << CountCriticalVotes(foo) << endl;
    cout << boolalpha << CountCriticalVotes(bar) << endl;    
}

答案 2 :(得分:1)

递归地执行它(顺便说一下非常低效。没理由这样做):

bool NumCriticalVotes :: CountCriticalVotes(Vector<int> const& blocks,
                                            int blockIndex,
                                            size_t current = 0)
{
    // check if we reach the end of the vector
    if (current == block.size())
    {
        return true;
    }

    int sum = blockIndex+block.get(current);

    if (sum >= 10)
    {
        return true;
    }

    return  CountCriticalVotes(blocks, blockIndex, current+1);
}

答案 3 :(得分:0)

也许我理解错了,但为什么不在这个函数中添加另一个参数:blocks中当前位置的索引。这样您就不必从向量中删除元素,也不必删除临时向量等。