Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is <algorithm> not needed for std::copy or std::swap?

Tags:

c++

algorithm

stl

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?

like image 499
bcf Avatar asked Mar 22 '23 02:03

bcf


1 Answers

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!

like image 123
templatetypedef Avatar answered Apr 26 '23 10:04

templatetypedef