lamc
lamc

Reputation: 367

STL algorithm and (end of) arrays

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?

Upvotes: 1

Views: 300

Answers (1)

Thibault BREZILLON
Thibault BREZILLON

Reputation: 111

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 accumulate function 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 the std::vector case.

Upvotes: 0

Related Questions