也许这是一个非常愚蠢的问题,但是我正在读的书指导我编写一段代码,使用算法对向量中的元素进行加扰和排序。为此,本书告诉我使用主 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;
}
它起作用的原因是因为它已包含在您也包含的标头中。
例如,向量可能在其源代码中包含算法。这很常见,因为它们通常只是标题。
也就是说,您不能依赖标准库的具体实现来在每个标头中包含相同的内容。 (例如, with 可能与 MSVC 一起使用,但可能与 gcc stdlibc+++ 一起使用)。
出于这个原因,我强烈建议包括您使用的内容,无论它将在哪里编译。 --- 请注意,这与“您引用的内容”略有不同,因为标头中的点和引用的前向声明可以显着缩短构建时间。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)