Home > Enterprise >  How to implement an iterator for a custom class?
How to implement an iterator for a custom class?

Time:03-03

For an assignment, we had to create custom list class. One of the functions is to insert an element into the middle of the list. So far I have,

 template<class T>
 class MyList : public list<T> {
 public:
   void addInMiddle(const T&);
   void insertInSortedOrder(const T&);
   void printList();
 };


template<class T>
void MyList<T>::addInMiddle(const T& x) {

 list<T>::iterator it = this->begin();

 int location = (this->size()) / 2;     //where we want to insert the new element
 for (int i = 0; i < location; i  ) {
     it  ;
 }
 this->insert(it,x);
}


 int main()
{
MyList<int> list1;
list1.push_back(1);
list1.push_back(2);
list1.push_back(3);
list1.push_back(4);
list1.addInMiddle(5);
list1.printList();
return 0;
}

The program compiles and shows 1,2,3,4. It should actually show 1,2,5,3,4. I don't think the iterator is working. Any thoughts?

CodePudding user response:

Your code works fine for me once I add typename in front of list<T>::iterator, since the type of the iterator is dependent on the type of the T template parameter, eg:

typename list<T>::iterator it = this->begin();

Online Demo

See Where and why do I have to put the "template" and "typename" keywords?

Alternatively, you can (and should) just use auto instead:

auto it = this->begin();

Online Demo


That being said, standard C containers are not intended to be inherited from (no virtual destructor, etc). You should use encapsulation instead of inheritance, eg:

template<class T>
class MyList {
private:
    list<T> m_list;
public:
    void addToBack(const T&);
    void addInMiddle(const T&);
    void insertInSortedOrder(const T&);
    void printList();
};

template<class T>
void MyList<T>::addToBack(const T& x) {
    m_list.push_back(x);
}

template<class T>
void MyList<T>::addInMiddle(const T& x) {

    list<T>::iterator it = m_list.begin();
    // or: auto it = m_list.begin();

    int location = m_list.size() / 2;     //where we want to insert the new element
    for (int i = 0; i < location; i  ) {
        it  ;
    }

    m_list.insert(it, x);
}

int main()
{
    MyList<int> list1;
    list1.addToBack(1);
    list1.addToBack(2);
    list1.addToBack(3);
    list1.addToBack(4);
    list1.addInMiddle(5);
    list1.printList();
    return 0;
}

Online Demo

  • Related