gpt4 book ai didi

c++ - 如何在 C++ 中为我自己的集合类添加 foreach 迭代支持?

转载 作者:搜寻专家 更新时间:2023-10-31 00:02:57 26 4
gpt4 key购买 nike

我已经创建了一个集合类型的 C++ 实现。我想添加迭代支持,以便开发人员可以在其上使用“for each”语句。我该怎么做?

最佳答案

标准用法是:公开类型 iteratorconst_iterator并提供至少两个功能,即begin()end()作为:

template</*.....*/>
class Collection
{
public:
typedef /*...*/ iterator;
typedef /*...*/ const_iterator;

iterator begin();
iterator end();

const_iterator begin() const;
const_iterator end() const;
};

一旦你实现了这些,你的收藏就可以在 std::for_each 中使用了。 ,以及在 <algorithm> 中定义的许多其他算法函数.

关于c++ - 如何在 C++ 中为我自己的集合类添加 foreach 迭代支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7082261/

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