迭代器模式

定义:提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

体会:迭代器在STL里面用到很多,vector, list都有迭代器,用的时候,我并不关心里面是怎么实现的,我只是循环地读取里面的值就可以了。如果后面我把存数据的集合由vector改成了list,对外面来说没有影响。因为外面只用到了迭代器。

实现:

class Iterator
{
public:
    virtual void first() = 0;
    virtual void last() = 0;
    virtual void next() = 0;
    virtual void prev() = 0;
};

using namespace std;
template <class T>
class MyVector : public vector<T>, public Iterator
{
public:
    MyVector() : vector<T>() { m_index = 0; }
public:
    void add(T value)
    {
        vector<T>::push_back(value);
    }

public:
    void first()
    {
        m_index = 0;
    }

    void last()
    {
        m_index = vector<T>::size() - 1;
    }

    void next()
    {
        if (m_index < vector<T>::size() - 1)
        {
            m_index++;
        }
    }

    void prev()
    {
        if (m_index > 0)
        {
            m_index--;
        }
    }

    T current()
    {
        return vector<T>::at(m_index);
    }

private:
    size_type m_index;
};
测试代码如下:

 MyVector<QAction *> m_List;
    QAction *ac1 = new QAction("ac1", this);
    m_List.add(ac1);
    QAction *ac2 = new QAction("ac2", this);
    m_List.add(ac2);
    QAction *ac3 = new QAction("ac3", this);
    m_List.add(ac3);

    qDebug() << m_List.current()->text();
    m_List.next();
    qDebug() << m_List.current()->text();
    m_List.last();
    qDebug() << m_List.current()->text();
    m_List.prev();
    qDebug() << m_List.current()->text();
    m_List.first();
    qDebug() << m_List.current()->text();
 

输出值为:

"ac1"

"ac2"

"ac3"

"ac2"

"ac1"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值