Question: Vector and Modulus error

Hello all, I'm having trouble understanding the nature of the error I'm getting. I wrote a function that checks a vector of ints for even numbers and any non-even number gets popped outside the vector. It then goes on to calculate the sum of this new vector's elements to return a total sum (calls a different function).

The problem is when I write the for loop to do the operation, it returns this error: "Unhandled exception at 0x7c812afb in euler.exe: Microsoft C++ exception: std::out_of_range at memory location 0x0012fae0.."

1
2
3
4
5
6
7
8
9
10
unsigned long int even(vector<int> vector){
	unsigned long int total = 0;
	for(int i=0;i<vector.capacity();i++){
		if(vector.at(i)%2 != 0)
			vector.pop_back();
	}
	display(vector);
	total = sum(vector);
	return total;
}



Anyone know what is causing this?
Last edited on
capacity() gives you the maximum possible size of a vector... which is determined by the memory available on a machine. This does not reflect the actual size of a vector. A vector with only 6 elements may have a capacity of several million.

Therefore you are stepping WAY outside the bounds of your vector.

You want to use size() instead of capacity()
Ah I see, thanks.
Topic archived. No new replies allowed.