1

I'm flicking through a set of C++ tutorials and am playing with the header includes for one of the examples. Why does the following still run, even with algorithm and vector commented out?

//#include <algorithm>
#include <iostream>
#include <random>
//#include <vector>

using namespace std;

int main() {
  vector<int>::const_iterator iter;

  cout << "Creating a list of scores.";
  vector<int> scores;
  scores.emplace_back(1500);
  scores.emplace_back(3500);
  scores.emplace_back(7500);

  cout << "\nHigh Scores:\n";

  for (iter = scores.begin(); iter!=scores.end(); iter++) {
    cout << *iter << endl;
  }

  cout << "\nFinding a score.";
  int score;
  cout << "\nEnter a score to find: ";
  cin >> score;
  iter = find(scores.begin(), scores.end(), score);
  if (iter!=scores.end()) {
    cout << "Score found.\n";
  } else {
    cout << "Score not found.\n";
  }

  cout << "\nRandomising scores.";
  random_device rd;
  default_random_engine generator(rd());
  shuffle(scores.begin(), scores.end(), generator);
  cout << "\nHigh Scores:\n";
  for (iter = scores.begin(); iter!=scores.end(); iter++) {
    cout << *iter << endl;
  }

  cout << "\nSorting scores.";
  sort(scores.begin(), scores.end());
  cout << "\nHigh Scores:\n";
  for (iter = scores.begin(); iter!=scores.end(); iter++) {
    cout << *iter << endl;
  }

  return 0;
}
junglie85
  • 1,243
  • 10
  • 30
  • 2
    The only way that can work is if the commented out headers are being implicitly included from somewhere else in your project. The compiler will fail if it can't find the definitions of `std::vector` and `std::find()`, so `` and `` are still required, whether you include them yourself or not. – Remy Lebeau Jul 19 '18 at 17:44
  • 4
    Standard headers are allowed to include any other standard headers but you aren't allowed to count on it. Another way to look at it is you are required to include the necessary headers but the compiler isn't required to fail if you don't. – François Andrieux Jul 19 '18 at 17:45
  • That's helpful for my understanding. Coming from a language which enforces the declaration of required dependencies, I was surprised to see that I could still get the above to compile. – junglie85 Jul 19 '18 at 17:52

1 Answers1

3

In C++ (unlike C) including any one standard header is allowed to do the equivalent of including any or all other standard headers. So, if you include <iostream> that can be equivalent to also including <algorithm>, <vector>, <string>, etc.

Early on, many compilers/libraries took advantage of this a great deal. Recently, they tend to be closer to a header only declaring/defining what it's required to, but there are still some headers that indirectly include at least some others.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111