0

int element配列のintをポップして保存し、配列から削除するこのコード行を取得しました。次に、return ステートメントで return CountCriticalVotes(rest, blockIndex + element);blockIndex変数に追加し、配列が空になる前に 10 に達すると 1 を返します。ただし、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 に答える