为什么 <algorithm> std::copy 或 std::swap 不需要?
Why is <algorithm> not needed for std::copy or std::swap?
根据这个 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>
的特定实现可能包括copy
和swap
的定义(可能通过包含<algorithm>
,或者可能包含包含它们的其他私有标头),但这只是一个实现细节,不能保证是可移植的。如果你要切换编译器,你完全有可能最终会使用C++标准库的实现,其中copy
和swap
不是由<vector>
导入的,在这种情况下,你的代码将不再编译。
换句话说,仅仅因为它碰巧适用于您的编译器并不意味着它是可移植的,因此为了获得最大的可移植性和正确性,无论如何都应该包含<algorithm>
。
希望这有帮助!
"导出由<vector>
"...
在C++中,不会导出内容。
但是,是的,<vector>
被允许 #include <algorithm>
,这意味着当您使用<vector>
时,您可以访问所有<algorithm>
。但为了安全起见,您仍然应该自己#include <algorithm>
,因为不同的实现(甚至不同的版本)可能不会这样做,如果您自己不包含它,它可能会破坏您的代码。
Clang Standard C++ 库中<vector>
的实现包括<algorithm>
. 值得注意的是,std::vector<T>
有一个swap()
的方法,所以这可能是一个线索。
请记住,在许多情况下,<algorithm>
算法在迭代器上工作,并且指针通常是可互换的。 在非 STL 容器的数据结构上使用其中包含的算法是完全可行的。
- a,b = b,a in python vs std::swap() in C++
- 使用 std::swap 禁用 ADL
- 如何使用 std::swap with array?
- 智能指针的 std::swap 是否保证引用保持不变?
- "std::swap"应用于这些对象时会做什么?
- 为什么 std::swap 不使用 swap 习语?
- 为什么有这么多std::swap的专业化
- 为什么使用std::swap不会在外部范围中隐藏其他交换函数
- 在结构C++中使用 std::swap 与 std::vector
- 为什么 std::swap 不适用于地址运算符
- std::swap vs std::exchange vs swap operator
- 使用静态tmp变量为简单类型C++重新实现std::swap()
- 使用 GCC 4.8 编译时无法对向量执行 std::swap
- 可以将"using std::swap;"放在标题中吗?
- "using std::swap"如何启用 ADL?
- std::swap 在 VS 2013 中导致无限递归
- 为什么不是 std::swap 在全局命名空间中
- std::swap(*(void **)x, *(void **)y)y是什么意思
- 在向量之间使用 std::swap 或 vector::swap
- 为什么 std::swap 不适用于模板项