C++ 中的自定义迭代器

Custom Iterator in C++(C++ 中的自定义迭代器)

本文介绍了C++ 中的自定义迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 TContainer 类,它是几个指向 TItems 类的 stl 集合指针的集合.

I have a class TContainer that is an aggregate of several stl collections pointers to TItems class.

我需要创建一个迭代器来遍历 TContainer 类中所有集合中的元素,抽象出内部工作的客户端.

I need to create an Iterator to traverse the elements in all the collections in my TContainer class abstracting the client of the inner workings.

这样做的好方法是什么?我应该创建一个扩展迭代器的类(如果是,我应该扩展哪个迭代器类),我应该创建一个迭代器聚合的迭代器类吗?

What would be a good way to do this?. Should I crate a class that extends an iterator (if so, what iterator class should I extend), should I create an iterator class that is an aggregate of iterators?

我只需要一个 FORWARD_ONLY 迭代器.

I only need a FORWARD_ONLY iterator.

即,如果这是我的容器:

I.E, If this is my container:

typedef std::vector <TItem*> ItemVector;
class TContainer {
   std::vector <ItemVector *> m_Items;
};

什么是遍历 m_Items 成员变量的向量中包含的所有项目的好的迭代器.

What would be a good Iterator to traverse all the items contained in the vectors of the m_Items member variable.

推荐答案

当我做自己的迭代器时(不久前),我继承自 std::iterator 并将类型指定为第一个模板参数.希望有所帮助.

When I did my own iterator (a while ago now) I inherited from std::iterator and specified the type as the first template parameter. Hope that helps.

对于前向迭代器,在以下代码中使用 forward_iterator_tag 而不是 input_iterator_tag.

For forward iterators user forward_iterator_tag rather than input_iterator_tag in the following code.

这个类最初取自 istream_iterator 类(并为我自己使用而修改,因此它可能不再类似于 istram_iterator).

This class was originally taken from istream_iterator class (and modified for my own use so it may not resemble the istram_iterator any more).

template<typename T>
class <PLOP>_iterator
         :public std::iterator<std::input_iterator_tag,       // type of iterator
                               T,ptrdiff_t,const T*,const T&> // Info about iterator
{
    public:
        const T& operator*() const;
        const T* operator->() const;
        <PLOP>__iterator& operator++();
        <PLOP>__iterator operator++(int);
        bool equal(<PLOP>__iterator const& rhs) const;
};

template<typename T>
inline bool operator==(<PLOP>__iterator<T> const& lhs,<PLOP>__iterator<T> const& rhs)
{
    return lhs.equal(rhs);
}

查看有关迭代器标签的文档:
http://www.sgi.com/tech/stl/iterator_tags.html

Check this documentation on iterator tags:
http://www.sgi.com/tech/stl/iterator_tags.html

刚刚重新阅读了有关迭代器的信息:
http://www.sgi.com/tech/stl/iterator_traits.html

Having just re-read the information on iterators:
http://www.sgi.com/tech/stl/iterator_traits.html

这是旧的做事方式 (iterator_tags),更现代的方法是为您的迭代器设置 iterator_traits<> 以使其与 STL 完全兼容.

This is the old way of doing things (iterator_tags) the more modern approach is to set up iterator_traits<> for your iterator to make it fully compatible with the STL.

这篇关于C++ 中的自定义迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++ 中的自定义迭代器

基础教程推荐