gpt4 book ai didi

c++ - 使用基于范围的 for 循环自定义容器遍历

转载 作者:行者123 更新时间:2023-12-01 13:03:57 30 4
gpt4 key购买 nike

在 C++ 中,一些 STL 容器,如 vector、map、string 可以被带有冒号的 for 循环遍历。

例如:
for(auto c:v)
当我在编写自定义容器时,我可以让它像 Java 那样遍历(只需要实现 Iterable)?

最佳答案

是的,您需要实现某种形式的迭代器并覆盖 std::begin(container) 和 std::end(container)(如果您的容器具有 begin 和 end 方法,也可能工作)。

在内部,代码等价于以下内容(这只是为了说明问题,编译器可以稍微不同地编写它,更多详细信息请参阅 here)。

auto _end = end(v);
for (auto _it = begin(v); _it != _end; ++_it) {
auto c = *_it;
<the rest of loop code>
}

因此,如果您的迭代器和覆盖按预期工作,它也适用于 for 循环。

关于c++ - 使用基于范围的 for 循环自定义容器遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61570936/

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