Deprecitus
Deprecitus

Reputation: 31

Null iterator end function?

From what I understand, the end function of an iterator should return null. When I try to return nullptr, the program crashes. Can someone explain how the end function should behave?

End()

LinkList::Iterator LinkList::end()
{
    return tail->next;
}

Update

Here's my LinkList class. The other two are nested inside it.

Class

class LinkList
{
public:

class Node
{
public:
    Node()
    {
        next = prev = NULL;
    }
    Node(int num)
    {
        data = num; next = prev = NULL;
    }

    int data;
    Node *next;
    Node *prev;
};

class Iterator
{
public:
    Iterator(Node* ptr);
    Iterator operator ++();
    int operator *();
    bool operator ==(Iterator it);
    bool operator !=(Iterator it);
    Node *ptr;
};

public:
    LinkList();
    virtual ~LinkList();
    LinkList(const LinkList& other);
    LinkList& operator=(LinkList& other);

    bool insert(int num);
    void insert(const initializer_list<int>& il);

    void merge(LinkList & src);
    Iterator *it;
    Iterator begin();
    Iterator end();

    int size();
    void clear();

private:
    Node *head, *tail, *temp;
    int count;
};

Upvotes: 0

Views: 905

Answers (1)

jmds
jmds

Reputation: 96

The end function of an iterator may or may not return nullptr, it depends on your implementation. For example, the end() function of STL vectors "point to" the position after the last element of the vector.

From the code you provided, I can't say what is causing your program to crash, but my bet would be that when you call the end() function, "tail" is nullptr. Check if that is the case.

EDIT:

After seeing your class, I agree that your Iterator::end() function should return nullptr. In your implementation you return tail->next, which in fact should be nullptr, but if tail itself is nullptr (i.e., there are no nodes in your list), your program will crash because you are trying to access a member of an object that is null. Just do:

LinkList::Iterator LinkList::end() {
    return nullptr;
}

Upvotes: 6

Related Questions