删除'#include <algorithm>'不会破坏代码

Dut*_*ner 3 c++ algorithm

也许这是一个非常愚蠢的问题,但我正在阅读的书指示我编写一段代码,使用算法对向量中的元素进行加扰和排序.为此,本书告诉我使用主C++库中的算法库.好吧,到目前为止,我理解它,但在编写代码之后,我想看看如果我从代码的顶部删除这个库会破坏什么,并且让我惊讶的是一切仍然有用.

这是我正在谈论的代码.当我从代码的顶部删除"#include算法"时,没有任何中断.怎么会这样?不使用这个库时,'random_shuffle'部分不应该被破坏吗?

#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cstdlib>
using namespace std;

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

    cout << "Creating a list of scores.";
    vector<int> scores;
    scores.push_back(1500);
    scores.push_back(3500);
    scores.push_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 << "\nRandomizing scores.";
    srand(static_cast<unsigned int>(time(0)));
    random_shuffle(scores.begin(), scores.end());
    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;
    }

    system("pause");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

111*_*111 7

它工作的原因是因为已经包含的标题包括在内.

例如,矢量可能在其源中包含算法.这很常见,因为它们通常只是标题.

也就是说,您不能依赖标准库的具体实现来在每个标头中包含相同的内容.(例如,可能与MSVC一起工作,它可能会破坏gcc stdlibc +++).

出于这个原因,我强烈建议包括你使用的内容,无论它在哪里编译都没有.---请注意,这与"您引用的内容"略有不同,因为标题中的点和引用的前向声明可以显着缩短构建时间.