gpt4 book ai didi

c++ - 为什么 std::copy 或 std::swap 不需要

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:29:23 24 4
gpt4 key购买 nike

根据这个cplusplus.com页,std::copy<algorithm> header ,原样 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> ,或者可能通过包含其他一些包含它们的私有(private) header ),但这只是一个实现细节,并不保证可移植。如果您要切换编译器,则完全有可能最终使用 C++ 标准库的实现,其中 copyswap不是由 <vector> 导入的,在这种情况下,您的代码将不再编译。

换句话说,仅仅因为它恰好在您的编译器上工作并不意味着它是可移植的,所以为了最大的可移植性和正确性,您应该包括 <algorithm>无论如何。

希望这对您有所帮助!

关于c++ - 为什么 std::copy 或 std::swap 不需要 <algorithm>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20939914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com