0

編集:少なくともエラーを整理し、コードを更新したようです。しかし、数学はまだうまくいっていないようです。何か案は?

要するに、私は C++ でプログラムを作成しようとしています。このプログラムは、ユーザーに最初のサークル内の人数を入力するように促し、k (カウントされた人数が実行される前に) = 3.

正しい考えだと思いますが、kを 1、2、または 5 以外として入力すると、「Debug Assertion Failed」および「Expression: vector erase iterator outside range」というエラーが表示されます。

// ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int n;//size of the circle
    vector <int> circle; //the circle itself

    //ask for how many people are in the circle
    cin >> n;

    //fill the circle with 1,2,3...n
    for (int idx = 0; idx < n; idx++)
    {
        circle.push_back (idx+1);
    }


    //cout << "The size of the circle is " << circle.size() << ".\nThe highest number is " << circle[n-1] << "."; //test to make sure numbers are being assigned properly to each vector element


    for (int count = 0, idx = 0; circle.size() > 1; idx++,count++)
    {
        //if the position (idx) is greater than the size of the circle, go back to the beginning of the circle and start counting again
        if (idx >= circle.size())
        {
            idx = 0;
        }

        //every time the counter reaches three, that person is executed
        if (count == 3)
        {
            circle.erase (circle.begin()+(idx));
            count = 0;
        }
    }

    cout << "The place to stand to win the hand is position #" << circle.front() << ".\n";

    return 0;
}
4

2 に答える 2

3

を確認してif (idx > circle.size())から、先に進んで に電話するだけcircle.erase (circle.begin()+(idx));です。の場合、この呼び出しは安全ではありませんidx == circle.size()

于 2015-04-27T20:12:14.537 に答える
0

@Pradhan は、元のエラーの解決策を既に提供しています (idx >= circle.size()の代わりにidx >= circle.size().

結果がまだ正しくない理由:
要素を消去するときは、それを補うためにインデックスを調整する必要があります (減算 1)。それ以外の場合、インデックスはベクトル内の次の要素に対応するため、事実上、常に 3 人ごとではなく 4 人ごとに実行されます。

コードの私のバージョンは次のとおりです。

#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

int main(){         
    int n;
    cin >> n;

    //fill the circle with 1,2,3...n
    vector <int> circle(n);
    std::iota(std::begin(circle), std::end(circle),1);

    int idx = -1;
    while (circle.size() > 1) {
        //advance by threee
        idx = (idx + 3) % circle.size();

        //execute Person 
        circle.erase(circle.begin() + (idx));

        //readjust to compensate for missing element
        --idx;
    }
    cout << "The place to stand to win the hand is position #" << circle.front() << ".\n";
}

もちろん、ループを次のように書き換えることができます

    int idx = 0;
    while (circle.size() > 1) {
        //advance by three
        idx = (idx + 2) % circle.size();

        //execute Person 
        circle.erase(circle.begin() + (idx));           
    }
于 2015-04-27T21:50:24.883 に答える