在C ++中编写我自己的stl-like迭代器实现 [英] Writing my own implementation of stl-like Iterator in C++

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

问题描述

晚上好,

我目前正试图理解迭代器在各种语言中的内在性,即它们的实现方式。

I'm currently trying to understand the intrinsics of iterators in various languages i.e. the way they are implemented.

例如,有以下类暴露列表界面。

For example, there is the following class exposing the list interface.

template<class T>
class List
{

    public:

    virtual void Insert( int beforeIndex, const T item ) throw( ListException ) =0 ;
    virtual void Append( const T item ) =0;   

    virtual T Get( int position ) const throw( ListException ) =0;
    virtual int GetLength() const =0;

    virtual void Remove( int position ) throw( ListException ) =0;


    virtual ~List() =0 {};
};

根据 GoF ,实现一个迭代器的最佳方式不同类型的遍历是创建基本的Iterator类(List的朋友)与受保护的方法,可以访问List的成员。 Iterator的具体实现将以不同的方式处理作业,并通过基本接口访问List的私有和受保护的数据。

According to GoF, the best way to implement an iterator that can support different kinds of traversal is to create the base Iterator class (friend of List) with protected methods that can access List's members. The concrete implementations of Iterator will handle the job in different ways and access List's private and protected data through the base interface.

从这里开始,情况变得混乱。说,我有LinkedList和ArrayList类,都是从List派生的,也有相应的迭代器,每个类都返回。如何实现LinkedListIterator?我绝对没有想法。基类迭代器类从List中检索什么类型的数据(这是一个简单的接口,而所有派生类的实现都有很大不同)?

From here forth things are getting confusing. Say, I have class LinkedList and ArrayList, both derived from List, and there are also corresponding iterators, each of the classes returns. How can I implement LinkedListIterator? I'm absolutely out of ideas. And what kind of data can the base iterator class retrieve from the List (which is a mere interface, while the implementations of all the derived classes differ significantly) ?

这么多杂乱。
谢谢。

Sorry for so much clutter. Thanks.

推荐答案

STL并不真正使用抽象基类和虚函数。相反,它被故意设计为不是OO(在GoF的意义上),完全建立在模板上,旨在编译时多态性。模板不关心抽象接口。事情的工作,只要他们有一个足够相似的接口(例如,如果你调用追加 push_back 预期符合STL标准的容器会为您工作,例如 std :: back_insert_iterator )。

STL doesn't really employ abstract base classes and virtual functions. Instead it is knowingly designed not to be OO (in the sense of GoF) and built entirely on templates, aiming for "compile-time polymorphism". Templates don't care about abstract interfaces. Things work as long as they have a sufficiently similar interface (e.g if you were to call Append push_back instead, more code expecting STL compliant containers would work for you, such as std::back_insert_iterator).

必须重载大量的操作符来表现得像一个指针(尽可能的,考虑到容器的限制),包括 * - > , ++ - (如果双向链接) $ c> == !=

A STL compliant iterator would have to overload lots of operators to behave like a pointer (as far as possible, given the limitations of the container), including *, ->, ++, -- (if bidirectional - doubly linked), == and !=.

这篇关于在C ++中编写我自己的stl-like迭代器实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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