模板迭代器,没有STL

Template iterator, no STL

本文关键字:没有 STL 迭代器      更新时间:2023-10-16

我不确定这在这里适合多少,我对c++有点陌生,但我必须用迭代器在动态数组/链表上创建ADT。我的问题是,有没有办法让这个迭代器成为模板这样它就可以同时适用于动态数组和链表或者我必须为一个类迭代器做两种不同的实现?

我在想这样的事情:

template<typename Container>
class Iterator {
private:
    Container *cont;
    int pos;
public:
    Iterator();
    Iterator(const Container& c);
    ~Iterator();
    bool isValid();
    void operator++();
    void operator--();
    Element getCurrent();
};

显然,它不知道Element是什么,这就是我的问题。是否有任何方法让getCurrent()从当前位置返回元素?这有什么结果吗?

在c++ 14中可以这样做:

template<typename Container>
class Iterator {
private:
    Container *cont;
    int pos;
public:
    Iterator();
    Iterator(const Container& c);
    ~Iterator();
    bool isValid();
    void operator++();
    void operator--();
    auto getCurrent(); // the return type is automatically generated
};

,但在c++11中你必须删除返回类型
所以getCurrent ();必须返回一个void *并使用reinterpret_cast(getCurrent());

实现修正:(what I think)

template<typename Container>
class Iterator {
private:
    Container *cont;
    int currentPos;
    int beginPos;
    int endPos;  
public:
    Iterator();
    Iterator(const Container& c,int endpos)currentPos{0},beginPos{0},endPos{endpos};
    ~Iterator();
    void operator++();
    void operator--(); 
    auto& getCurrent()const;
}