c++ - 尽管注释掉了所需的头文件,为什么这个 C++ 程序仍能编译和运行?
问题描述
我正在浏览一组 C++ 教程,并且正在使用其中一个示例的标题包含。为什么以下仍然运行,即使有algorithm
并vector
注释掉?
//#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 不同)中,包含任何一个标准头文件都可以等同于包含任何或所有其他标准头文件。所以,如果你包括<iostream>
那可以等同于包括<algorithm>
, <vector>
, <string>
, 等等。
早期,许多编译器/库充分利用了这一点。最近,它们往往更接近于仅声明/定义所需内容的标头,但仍有一些标头至少间接包含其他一些标头。
推荐阅读
- apache - httpd (apache) - 重写页面 -> 查询参数
- python - 为什么 map(outer.remove, inner) 不能从外部移除内部?
- python - 我想用这个人的名字创建一个文件,我怎样才能没有错误?
- windows - 拖动文件夹时资源管理器冻结,直到 VB 事件完成
- java - 如何修复这个 if-then 结构以根据需要跳出循环?
- rust - 引用和变异 id_tree Rust 的问题
- python - 如何在python中将字符串日期(2021年1月25日)转换为ymd日期(2021-01-01)
- r - R Markdown文档中所有方程式中的显示样式文档整个文档
- javascript - JS:3个滚动条同步
- wpf - 订阅任何没有子控件实例的冒泡 WPF 子控件路由事件