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