According to this cplusplus.com page, std::copy
is in the <algorithm>
header, as is std::swap
and yet this works:
#include <iostream> // std::cout
#include <vector> // std::vector
#include <iterator> // std::ostream_iterator()
#include <cstdlib> // rand(), srand()
// NOT including <algorithm>
int main()
{
srand(time(NULL));
const int SIZE = 10;
std::vector<int> vec;
for(int i = 0; i < SIZE; ++i)
{
vec.push_back(rand() % 256);
}
copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}
The only thing I could think of is that they are exported by <vector>
as well...but then why do we need the <algorithm>
header at all?
The particular implementation of <vector>
that you're using here probably includes definitions for copy
and swap
(possibly by including <algorithm>
, or possibly by including some other private header that contains them), but that's just an implementation detail and isn't guaranteed to be portable. It's entirely possible that if you were to switch compilers, you'd end up using an implementation of the C++ standard libraries where copy
and swap
weren't imported by <vector>
, in which case your code will no longer compile.
In other words, just because it happens to work on your compiler doesn't mean it's portable, so for maximum portability and correctness you should include <algorithm>
anyway.
Hope this helps!
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