Maybe this is a very silly question, but the book I'm reading instructed me to write a piece of code that uses algorithms to scramble and order the elements in a vector. To do this the book tells me to use the algorithms library from the main C++ library. Alright, so far I understand it, but after writing the code I wanted to see what would break if I would remove this library from the top-part of my code, and it surprised me that everything still worked.
This is the code I'm talking about. When I remove '#include algorithm' from the top-part of the code, nothing breaks. How can this be? Isn't the 'random_shuffle' part supposed to break when not using this library?
#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;
}
The reason it works is because has been included by a header that you have also included.
For example vector might have included algorithms in it's source. This is common as they are often header only.
That said, you can not rely on the specific implementation of the standard library to have the same includes in each header. (for example with might work with MSVC and it might break with gcc stdlibc+++).
For this reasons I highly recommend including what you use, regardless of where it will compile of not. --- note that this is slightly different to 'what you reference' because forward declaration for point and references in headers can significantly improve build time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With