1

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?

lamc
  • 347
  • 2
  • 5
  • Pointers to array elements meet the requirements to be a [LegacyInputIterator](https://en.cppreference.com/w/cpp/named_req/InputIterator), which means that you can use pointers to the beginning and after-the-end of an array the same way you'd use iterators for a container. – Nathan Pierson Jul 30 '22 at 05:49
  • See also [advantages of `std:array` over array](https://stackoverflow.com/a/30263398/9233560) – gkhaos Jul 30 '22 at 05:52
  • The program doesn't know. It's just comparing like `for (; first != last; ++first) { ... }`. – songyuanyao Jul 30 '22 at 05:56
  • 2
    Since the standard specifies that array elements are contiguous, the programmer (not the compiler) knows that (for an array with three elements) `a + 3` points one past the end. Incidentally, you can do `accumulate(begin(a), end(a), 0)` in C++11 and later (not before) whether `a` is a raw array, or any standard container (e.g. `vector`, `array`, `list`, `string`) and let the compiler work out the ranges. – Peter Jul 30 '22 at 09:18

1 Answers1

0

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.