fork(3) download
  1. #include <iostream>
  2. #include <list>
  3. using namespace std;
  4.  
  5. template<class T>
  6. class MyList : public list<T> {
  7. public:
  8. void addInMiddle(const T&);
  9. void printList();
  10. };
  11.  
  12. template<class T>
  13. void MyList<T>::addInMiddle(const T& x) {
  14.  
  15. typename list<T>::iterator it = this->begin();
  16.  
  17. int location = (this->size()) / 2; //where we want to insert the new element
  18. for (int i = 0; i < location; i++) {
  19. it++;
  20. }
  21. this->insert(it,x);
  22. }
  23.  
  24. template<class T>
  25. void MyList<T>::printList() {
  26. for (const auto &elem : *this) {
  27. cout << elem << " ";
  28. }
  29. cout << endl;
  30. }
  31.  
  32. int main()
  33. {
  34. MyList<int> list1;
  35. list1.push_back(1);
  36. list1.push_back(2);
  37. list1.push_back(3);
  38. list1.push_back(4);
  39. list1.addInMiddle(5);
  40. list1.printList();
  41. return 0;
  42. }
Success #stdin #stdout 0.01s 5532KB
stdin
Standard input is empty
stdout
1 2 5 3 4