简体   繁体   English

模板迭代器,无STL

[英]Template iterator, no STL

I'm not sure how much this fits in here and I'm kinda new to C++ but I have to make an ADT over a dynamic array/linked list with iterators. 我不确定这是否适合这里,我对C ++还是有点陌生​​,但是我必须在带有迭代器的动态数组/链接列表上进行ADT。 My question is, is there a way to make this iterator a template so it could work for both the dynamic array and the linked list or I have to make 2 different implementations for a class Iterator? 我的问题是,有没有办法使此迭代器成为模板,以便它既可以用于动态数组又可以用于链表,或者我必须为类迭代器进行2种不同的实现?

I was thinking of something like this: 我在想这样的事情:

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

};

Now clearly, it has no idea what Element is and that's my problem. 现在很明显,它不知道什么是元素,这就是我的问题。 Is there any way to have getCurrent() to return the element from the current position? 有什么方法可以让getCurrent()从当前位置返回元素? Is this going anywhere? 这会去哪里吗?

in c++ 14 you can do this : 在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

};

but in c++11 you have to erase the return type 但是在c ++ 11中,您必须删除返回类型
so getCurrent(); 所以getCurrent(); must return a void * and use reinterpret_cast(getCurrent()); 必须返回一个空*并使用reinterpret_cast(getCurrent());

implementation correction: (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;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM