Problem with vectors

Hello,

I need to implement function that calculates sum of the first and last item in the vector, then the sum of second and second-last item in the vector, and so on, until all integers in the vector have been processed. With input 1 2 3 4 ! the output will be 5 5, followed by newline. The function stops reading when first non-numeric value is given by the user. Why the following code does not work ? Thanks for the tips in advance :)

1
2
3
4
5
6
7
8
9
10
11
12
 void printSum2(std::vector<int>& v) {

	auto begin = v.begin();
	auto end = v.end();
	int i = 0;
	while (i < (v.size() / 2)) {
		int sum = *(begin + i) + *(end - i);
		std::cout << sum << " ";
		i++;
	}
	std::cout << std::endl;
}
Last edited on
You making an out of bounds reference in line 7.

 
*(end - i) 

end() points past the end of the vector (not to the last element). On the first iteration i is 0, therefore you're trying to reference an element past the end of the vector.
Thanks very much!
I just changed *(end-i)--->*(end-1-i) and now it works.
Topic archived. No new replies allowed.