I am new to C++. I was trying using the accumulate algorithm from the numeric library. Consider the following code segment.
int a[3] = {1, 2, 3};
int b = accumulate(a, a + 3, 0);
It turns out that the code segment works and b gets assigned 1+2+3+0=6.
If a was a vector<int> instead of an array, I would call accumulate(a.begin(), a.end(), 0). a.end() would point to one past the the end of a. In the code segment above, a + 3 is analogous to a.end() in that a + 3 also points to one past the end of a. But with the primitive array type, how does the program know that a + 3 is pointing at one past the end of some array?
The end iterator is merely used for comparison as a stop marker, it does not matter what it really points to as it will never be dereferenced. The
accumulatefunction will iterate over all elements in the range [a, a+3[ and stop as soon as it encounters the stop marker. In the C-style array case, the stop marker will be the element one past the end of the array. This would be the same in thestd::vectorcase.