gpt4 book ai didi

c++ - 是否必须包含 header 才能使用 begin 和 end 函数?

转载 作者:太空狗 更新时间:2023-10-29 20:36:21 24 4
gpt4 key购买 nike

要获得指向数组第一个和最后一个元素的指针,我们可以使用 begin 和 end 函数:https://stackoverflow.com/a/14595314/5761266

但是,我注意到如果我省略 #include <iterator>,程序编译得很好.为什么会这样,因为这些函数是在 <iterator> 中定义的标题?

我使用的唯一 header 是 <iostream> .
我使用的程序:http://coliru.stacked-crooked.com/a/28b2b449aae19a47

最佳答案

函数的返回类型必须事先完全定义。这意味着迭代器 header 必须包含在定义 begin() 的任何可迭代对象中。和 end()方法并返回一个完整的迭代器对象*

这意味着每当您使用标准容器(例如 std::vectorstd::mapstd::list 等)时,标准库头文件必须 #include <iterator> begin() 之前的某处和 end()声明了方法。

因此您不需要 #include <iterator>你自己,因为通过做#include <vector> (例如)您也会自动包含 iterator.h。

请记住,当您 #include头文件,则该头文件中包含的任何其他头文件自动为 #include d 也在你的代码文件中。


*除非迭代器类型完全自定义且不使用 standard iterator hierarchy categories .

关于c++ - 是否必须包含 header <iterator> 才能使用 begin 和 end 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38926640/

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