定义:提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
体会:迭代器在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"