Error: Vector subscript out of range

Hi,

I think I'm really close to solving the Josephus problem for my beginning programming class, but I am having one problem with my playGame method. I need my startcount to be -1 so that, when adding m, you get the index of the person who will die next. Also, in order to loop around the circle (of the vector), I am trying:

1
2
3
4
5
int startcount = -1;
if (startcount > names.size()){ 
	startcount = startcount % names.size(); //gives remainder
        startcount = startcount - 1; //remainder - 1
}


I'm getting the run-time error "Error: Vector subscript out of range" when I run it. Any ideas? Thanks for your time!

Here's the whole method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
vector<string> Circle::playGame(int n, int m){//n is people. m is counting number.
	getNames();
	if(n < 10 && n > 20 && m < 1){
		return dead;
	}else{
		for(int i = 20; i > n; i--){ //gets vector to size of players
			names.pop_back();
		}
		int startcount = -1;//this needs to be changed from 0 to -1 because it's not starting right, but it's not letting me change it yet.
		for(int i = 0; names.size() > 0; i++){
			startcount = startcount + m;
			if (startcount > names.size()){ //remember to cout the names when the die -> probably need to return a vector of the dead people and will return that vector
				startcount = startcount % names.size(); //gives remainder
				startcount = startcount - 1; //remainder - 1
			}
			//next I need to erase at startcount
			string todie = names[startcount]; //assigns the name of the one to die to todie.
			dead.push_back(todie); //adds that todie name to the dead vector.
			names.erase(names.begin() + startcount); //give it an iterator of startcount.
		}
	}
	return dead;
Last edited on
Topic archived. No new replies allowed.