Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

To obtain a pointer to the first and last elements of an array, we can use the begin and end functions: https://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 <iterator> header?

The only header I used is <iostream>.
The program I used: http://coliru.stacked-crooked.com/a/28b2b449aae19a47

like image 578
S Wang Avatar asked Jan 06 '23 13:01

S Wang


2 Answers

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 hierarchy categories.

like image 135
Karl Nicoll Avatar answered Feb 01 '23 00:02

Karl Nicoll


It is very likely that in the C++ implementation you are using one of the other headers you have included includes <iterator>. Do not expect this to be the same in other C++ implementations or even the next revision of the implementation you are using.

Best practice is to always include all headers you need in whichever file needs them.

This prevents problems and mystery bugs in the future should an include be removed from another included header or what looks like an include turns out to merely be a forward declaration of key classes or functions.

This also assists greatly in portability. The next tool chain you use could be laid out differently, not to mention other programmers who may inherit your code or wish to use it in another project.

From the student coder point of view, it really sucks when you hand in code that compiles on your PC, but not the marker's.

This sounds silly and repetitive, but a properly written header has include guards to prevent the header from being included more than one in any translation unit.

This also leaves breadcrumbs for other developers who can see at a glance what headers are used by a given file. For this reason do not include everything just in case you might need it. Creating a monolithic list of unnecessary headers also slows compilation.

like image 30
user4581301 Avatar answered Jan 31 '23 22:01

user4581301