首页 > 解决方案 > 尽管注释掉了所需的头文件,为什么这个 C++ 程序仍能编译和运行?

问题描述

我正在浏览一组 C++ 教程,并且正在使用其中一个示例的标题包含。为什么以下仍然运行,即使有algorithmvector注释掉?

//#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;
}

标签: c++

解决方案


在 C++(与 C 不同)中,包含任何一个标准头文件都可以等同于包含任何或所有其他标准头文件。所以,如果你包括<iostream>可以等同于包括<algorithm>, <vector>, <string>, 等等。

早期,许多编译器/库充分利用了这一点。最近,它们往往更接近于声明/定义所需内容的标头,但仍有一些标头至少间接包含其他一些标头。


推荐阅读