C ++中的自定义迭代器 [英] Custom Iterator in C++

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

问题描述

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

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

我需要创建一个Iterator遍历所有集合中的元素在我的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?

I只需要一个FORWARD_ONLY迭代器。

I only need a FORWARD_ONLY iterator.

IE,如果这是我的容器:

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);
}

在迭代器标签上查看此文档:

< a href =http://www.sgi.com/tech/stl/iterator_tags.html> 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 ++中的自定义迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆