Question on headers

In the coding below, the copy statement works without #include <algorithm> being specified. I also notice this in another program that initializer_list could be used without its header being specified. Why so?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <list>
#include <iterator>

using namespace std;

int main()
{
    list<int> l {1, 2, 3, 4, 5};

    copy(l.rbegin(), l.rend(), ostream_iterator<int>{cout, ", "});
    std::cout << '\n';

    copy(make_reverse_iterator(end(l)),
         make_reverse_iterator(begin(l)),
         ostream_iterator<int>{cout, ", "});
    std::cout << '\n';
}
Probably, because in the implementation of C++ that you're using, those headers are included by other headers that you're still using.

So, for example, it may be that <initializer_list> is included by <list>, or one of the other headers.
> the copy statement works without #include <algorithm> being specified.

One standard library header may include all or parts of other standard library headers; this is expressly permitted by the standard. In this case, one of the other standard headers which were include would have indirectly included the particular overload of std::copy()


> I also notice this in another program that initializer_list could be used without its header being specified.

The header <initializer_list> is automatically included if we have #include <list>
(or #include of any other standard container). This is required by the standard.

26.3.5 Header <list> synopsis

1
2
3
4
5
6
7
#include <initializer_list>

namespace std {
  // [list], class template list
  template<class T, class Allocator = allocator<T>> class list;

  // ... 

http://eel.is/c++draft/list.syn
Thank you, Mickey!

Thank you for the link, JL! It is solid proof that the list header includes the initializer_list header.

You're welcome - glad I could help.
Topic archived. No new replies allowed.