为什么 <algorithm> std::copy 或 std::swap 不需要?

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

本文关键字:std swap 不需要 copy gt 为什么 lt algorithm      更新时间:2023-10-16

根据这个 cplusplus.com 页面,std::copy<algorithm>标题中,就像std::swap一样,但这有效:

#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";
}

我唯一能想到的是它们也是<vector>出口的......但是为什么我们需要<algorithm>标头呢?

您在此处使用的<vector>的特定实现可能包括copyswap的定义(可能通过包含<algorithm>,或者可能包含包含它们的其他私有标头),但这只是一个实现细节,不能保证是可移植的。如果你要切换编译器,你完全有可能最终会使用C++标准库的实现,其中copyswap不是由<vector>导入的,在这种情况下,你的代码将不再编译。

换句话说,仅仅因为它碰巧适用于您的编译器并不意味着它是可移植的,因此为了获得最大的可移植性和正确性,无论如何都应该包含<algorithm>

希望这有帮助!

"导出由<vector>"...

在C++中,不会导出内容。

但是,是的,<vector>被允许 #include <algorithm> ,这意味着当您使用<vector>时,您可以访问所有<algorithm>。但为了安全起见,您仍然应该自己#include <algorithm>,因为不同的实现(甚至不同的版本)可能不会这样做,如果您自己不包含它,它可能会破坏您的代码。

Clang Standard C++ 库中<vector>的实现包括<algorithm> . 值得注意的是,std::vector<T>有一个swap()的方法,所以这可能是一个线索。

请记住,在许多情况下,<algorithm>算法在迭代器上工作,并且指针通常是可互换的。 在非 STL 容器的数据结构上使用其中包含的算法是完全可行的。