简体   繁体   中英

hasNext() method in array iterator

that is my generic Array header file:

#ifndef ARRAY_H
#define ARRAY_H
#include "Number.h"
#include "Iterator.h"

//array is contius memory of numbers
class Array{
protected:
    //array has some contius cell of memory each include the data
    class Cell{
    public:
        Number* m_data;

        //c'tor:(inline)
        Cell(Number* num=NULL): m_data(num){};
        //D'tor (inline)
        ~Cell(){};
    };
    //composition class of iterator:
    class ArrayIterator:public Iterator{
    public:
        Cell* m_current;

        //C'tor:(inline)
        ArrayIterator(Cell* cell):m_current(cell){};
        //D'tor:
        ~ArrayIterator(){};

        //is there any next numbers
        bool hasNext()const;
        //is there any prev numbers
        bool hasPrev()const;

        //returning the current and getforward
        Number& next();
        //returning the current and getback
        Number& prev();

    };
    Cell* m_head,*m_last;
public:
    //C'tor:
    Array(const int amount);
    //D'tor:
    virtual ~Array(){delete[]m_head;};


    //Random access operator:
    Number& operator [] (const int i)const{return *m_head[i].m_data;};


};


#endif

consider Number and Iterator as abstract classes and Number represent a generic number.

my question: how to implement hasNext() in ArrayIterator, because the ArrayIterator is a composition class and it dont "know" the size of the array

To implement the hasNext() and hasPrev() methods, the ArrayIterator needs to know where the bounds are of the current Array it is iterating over.

This can be done by either storing Cell* m_head,*m_last along with m_current in the ArrayIterator , or by storing a pointer to the Array object and arranging that the ArrayIterator has access to the m_head and m_last of the Array object. In either case, you need to store additional information in the ArrayIterator .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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