【问题标题】:hasNext() method in array iterator数组迭代器中的 hasNext() 方法
【发布时间】:2013-05-22 07:12:08
【问题描述】:

这是我的通用数组头文件:

#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

将 Number 和 Iterator 视为抽象类,而 Number 表示一个通用数字。

我的问题:如何在 ArrayIterator 中实现 hasNext(),因为 ArrayIterator 是一个组合类,它不“知道”数组的大小

【问题讨论】:

  • 您应该将结尾传递给迭代器或用特殊数字标记结尾。
  • 这就是为什么在 C++ 标准库中没有hasNext 而只有my_iterator != end(其中end 是另一个迭代器,例如指向m_last+1)。
  • hansmaad- 你的意思是在迭代器中创建新的 size 属性吗?这可能会解决问题,但会使内存更大,而且迭代器经过特定单元格,它不知道该特定单元格的位置
  • 你会发现 C++ 程序员被 Java 风格的迭代器弄糊涂了,就像 Java 程序员被 C++ 风格的迭代器弄糊涂一样。

标签: c++ arrays generics iterator


【解决方案1】:

要实现hasNext()hasPrev() 方法,ArrayIterator 需要知道它正在迭代的当前Array 的边界在哪里。

这可以通过在ArrayIterator 中存储Cell* m_head,*m_lastm_current 来完成,或者通过存储指向Array 对象的指针并安排ArrayIterator 可以访问m_headArray 对象的m_last。无论哪种情况,您都需要在ArrayIterator 中存储其他信息。

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 2010-12-30
    • 2020-12-30
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 2020-12-15
    相关资源
    最近更新 更多