I am writing a program for a class with the following description:
"Eve was a beautiful Princess, and many suitors came courting her. She decided that the following procedure would decide who she would marry. She would line the men up, and give them a number based on their position (1 for first in line, 2 for second, and so on). Whenever she reached the third person in line, that person would be elimated from the line. Whenever she reached the end of the line, she would continue counting from the beginning. The last person in line would have the honor of marrying her."
The problem is, every time I run the code, I get an outrageously large number as my answer. Testing with cout shows that the program doesn't touch the contents of the while loop. When the while loop is removed, the program crashes with 'vector iterator + offset out of range' and "Standard C++ libraries out of range".
I understand that there is something wrong within the while loop itself that makes the program crash, and I have been working on it for days to try to figure out what. What I do not understand is why the program ignores the while loop in the first place. Any and all advice would be greatly appreciated.
// EveSuitor.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
class EveSuitor
{
vector<int> newList;
public:
EveSuitor::EveSuitor(vector<int> list)
{
vector<int> newList = list;
}
void setUpSuitors(vector<int>list);
int chooseWinner(vector<int>list);
int suitorCounter;
int suitorTotal;
};
void EveSuitor::setUpSuitors(vector<int>v)
{
int numOfSuitors;
cout<< "Enter in the number of suitors that are there: ";
cin>> numOfSuitors;
for (int i = 0; i < numOfSuitors; i++)
{
v.push_back(i);
}
for (unsigned int j = 0; j < v.size(); j++)
{
cout<< v[j] << " ";
}
}
int EveSuitor::chooseWinner(vector<int>v)
{
while (v.size() > 1)
{
v.erase(v.begin()+suitorTotal);
for (unsigned int j = 0; j < v.size(); j++)
{
cout<< v[j] << " ";
}
suitorTotal = suitorTotal + suitorCounter;
if (suitorTotal > v.size())
{
suitorCounter = suitorTotal - v.size();//This will reset the counter for the suitor, so that it will move on to the next suitor at the beginning of the list.
suitorTotal = 0;
}
else
{
suitorCounter = suitorCounter + 3;
suitorTotal = suitorTotal + 3;
}
}
if (v.size() == 1)
{
return v[0];
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int suitorTotal = 3;
int suitorCounter = 3;
vector<int>listOfSuitors;
EveSuitor list(listOfSuitors);
list.setUpSuitors(listOfSuitors);
int winner = list.chooseWinner(listOfSuitors);
cout<<"The position you should be at is: " << winner;
return 0;
}