为什么< algorithm>std :: copy或std :: swap是否不需要? [英] Why is <algorithm> not needed for std::copy or std::swap?

查看:68
本文介绍了为什么< algorithm>std :: copy或std :: swap是否不需要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此 cplusplus.com 页的 std :: copy std :: swap 一样,位于< algorithm> 标头中,但这仍然有效:

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

我唯一想到的是它们也由< vector> 导出...但是为什么我们需要< algorithm> 头文件吗?

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?

推荐答案

您在此处使用的< vector> 的特定实现可能包括 copy 的定义和 swap (可能是通过包含< algorithm> ,或者可能是通过包含一些其他包含它们的私有标头)来实现的,但这仅是实现细节,不能保证便于携带.完全有可能,如果要切换编译器,最终将使用C ++标准库的实现,其中 copy swap 不由导入.< vector> ,在这种情况下,您的代码将不再编译.

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.

换句话说,仅仅因为它恰好可以在您的编译器上运行并不意味着它是可移植的,所以为了获得最大的可移植性和正确性,您仍然应该包括< algorithm> .

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.

希望这会有所帮助!

这篇关于为什么&lt; algorithm&gt;std :: copy或std :: swap是否不需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆