S Wang S Wang - 2 months ago 8
C++ Question

Is it necessary to include header <iterator> to use begin and end functions?

To obtain a pointer to the first and last elements of an array, we can use the begin and end functions: http://stackoverflow.com/a/14595314/5761266

However, I notice that the program is compiled just fine if I omit the

#include <iterator>
. Why is this the case since these functions are defined in the

The only header I used is

The program I used: http://coliru.stacked-crooked.com/a/28b2b449aae19a47


A function's return type must be fully defined beforehand. This means that the iterator header must be included with any iterable object that defines a begin() and end() method and returns a complete iterator object*.

What this means is that whenever you use a standard container (e.g. std::vector, std::map, std::list, etc) the standard library header files must #include <iterator> somewhere before the begin() and end() methods are declared.

Therefore you won't need to #include <iterator> yourself, because by doing #include <vector> (for example) you are automatically including iterator.h as well.

Remember that when you #include a header file, any other header files included within that header file are automatically #included in your code file as well.

*Unless the iterator type is completely custom and does not use standard iterator heirarchy categories.