0

我得到了这行代码,它弹出数组的一个 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

4 回答 4

1

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

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

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

于 2012-12-11T05:09:19.397 回答
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;    
}
于 2012-12-11T05:23:28.160 回答
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);
}
于 2012-12-11T05:26:46.833 回答
0

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

于 2012-12-11T05:06:23.120 回答