Insert and Erase Operators

The powerful part of list is "the efficient insertion and deletion".  (Think about array and vector)

The insert and erase member functions of class list:

Eample1:
2 - 7 - 3 - 9 - 5         old list
    ^
    |
    iter

Insert 4 before 7:
2 - 4 - 7 - 3 - 9 - 5     new list
    ^   ^
    |   |
    |   iter
    newElt

#include <iostream>
#include <list>

using namespace std;

void main()
{
 int arr[5] ={2, 7, 3, 9, 5};
 list<int> LIST1(arr, arr+5);
 list<int>::iterator iter, newElt;
 iter = LIST1.begin();

 while( iter != LIST1.end())
 {
  cout<<*iter<<" ";
  iter++;
 }
 cout<<endl;

 iter = LIST1.begin();
 iter++;
 newElt = LIST1.insert(iter, 4);
 cout<<"content of newElt point to = "<<*newElt<<endl;
 cout<<"content of iter point to = " <<*iter<<endl;

 iter = LIST1.begin();
 while( iter != LIST1.end())
 {
  cout<<*iter<<" ";
  iter++;
 }
 cout<<endl;
}



Eample2:
2 - 7 - 3 - 9 - 5         old list
    ^
    |
    iter


2 - 3 - 9 - 5             new list
               ??
              /
             iter


OR  (Use iter++ to locate iter)
2 - 3 - 9 - 5             new list
    ^
    |
    iter


#include <iostream>
#include <list>

using namespace std;

void main()
{
 int arr[5] ={2, 7, 3, 9, 5};
 list<int> LIST1(arr, arr+5);
 list<int>::iterator iter, newElt;
 iter = LIST1.begin();

 while( iter != LIST1.end())
 {
  cout<<*iter<<" ";
  iter++;
 }
 cout<<endl;

 iter = LIST1.begin();
 iter++;
 LIST1.erase(iter);

 iter = LIST1.begin();
 while( iter != LIST1.end())
 {
  cout<<*iter<<" ";
  iter++;
 }
 cout<<endl;
}



#include <iostream>
#include <list>

using namespace std;

void main()
{
 int arr[5] ={2, 7, 3, 9, 5};
 list<int> LIST1(arr, arr+5);
 list<int>::iterator iter, newElt;
 iter = LIST1.begin();

 while( iter != LIST1.end())
 {
  cout<<*iter<<" ";
  iter++;
 }
 cout<<endl;

 iter = LIST1.begin();
 iter++;
 LIST1.erase(iter++);
 cout<<"content of iter point to = " <<*iter<<endl;

 iter = LIST1.begin();
 while( iter != LIST1.end())
 {
  cout<<*iter<<" ";
  iter++;
 }
 cout<<endl;
}



Example of erasing whole list:
#include <iostream>
#include <list>

using namespace std;

void main()
{
 int arr[5] ={2, 7, 3, 9, 5};
 list<int> LIST1(arr, arr+5);
 list<int>::iterator iter, newElt;
 iter = LIST1.begin();

 while( iter != LIST1.end())
 {
  cout<<*iter<<" ";
  iter++;
 }
 cout<<endl;

 LIST1.erase(LIST1.begin(), LIST1.end());
 cout<<"The number of elements after erased in LIST1 is "
     <<LIST1.size()<<endl;
}