Wednesday, May 11, 2011

STL list iterator example c++

An example showing how to use STL list iterator. A STL list iterator is used to specify the location in the list where an items will be inserted or deleted. [STL list iterator]

#include <iostream.h>
#include <list>
void print(list <char> );// elsewhere
main()
{ list <char> l;
list <char>::iterator p;
l.push_back('o'); l.push_back('a'); l.push_back('t');
p=l.begin();
cout <<" "<< *p<<endl;  // p refers to the 'o' in ('o', 'a', 't')
print(l);
l.insert(p, 'c');
// l is now ('c', 'o', 'a', 't') and p still refers to 'o'
cout <<" "<< *p<<endl;
print(l);
l.erase(p);
cout <<" "<< *p<<endl; // p refers to an 'o' but it is not in l!
print(l);
l.erase(l.begin()); //removes front of l
print(l);
}