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?