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

两盒软妹~` 提交于 2021-02-08 20:37:07

问题


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?


回答1:


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!




回答2:


"exported by <vector>"...

In C++, things aren't exported.

But yeah, <vector> is allowed to #include <algorithm>, which means you get access to all of <algorithm> when you use <vector>. But to be safe, you should still #include <algorithm> yourself, as a different implementation (or even a different version) may not do this, and if you don't include it yourself it could break your code.




回答3:


The implementation of <vector> in the Clang Standard C++ library includes <algorithm>. Notably, std::vector<T> has a swap() method, so this might be a clue why.

Remember that algorithms in <algorithm> work, in many cases, on iterators, and that pointers are often interchangeable. It's perfectly feasible to be using the algorithms contained within on data structures that are not STL containers.



来源:https://stackoverflow.com/questions/20939914/why-is-algorithm-not-needed-for-stdcopy-or-stdswap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!