EDIT: I seem to have sorted out the errors, at the very least, and have updated the code. However, the math still doesn't seem to be working out. Any ideas?
In short, I'm trying to write a program in C++ that will prompt the user for the number of people in the initial circle, and then tell them in which position they should stand in order to survive if k (the number of people counted to before being executed) = 3.
I've got what I think is the right idea, but I get the error "Debug Assertion Failed" and "Expression: vector erase iterator outside range" if I input k as anything other than 1, 2, or 5.
// 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;
}
You only check for if (idx > circle.size())
and then go ahead and call circle.erase (circle.begin()+(idx));
. This call isn't safe when idx == circle.size()
.