std::list and STL containers

Dr. Lawlor, CS 202, CS, UAF

std::list is useful to store a list of objects, where you need to both add and remove objects from the list.  Unlike vector, it's efficient to add new elements to the middle of a list.  Here's the basic interface, which looks extremely similar to std::vector:
#include <list>

int foo(void) {
std::list<string> l;
l.push_back("alphonse");
l.push_back("denise");
l.push_back("charlie");
cout<<"List's front == "<<l.front()<<"\n";
cout<<"List's back == "<<l.back()<<"\n";
return 0;
}

(Try this in NetRun now!)

The way you access the elements of a list is with an "iterator", which acts like a pointer into the list.  You move the iterator forward with "++it", and dereference the iterator with "*it".  The iterator starts at "l.begin()", and runs all the way until it hits "l.end()".  Typically these are combined into a very weird looking for loop, like so:
#include <list>

int foo(void) {
std::list<string> l;
l.push_back("alphonse");
l.push_back("denise");
l.push_back("charlie");
for (std::list<string>::iterator it=l.begin();it!=l.end();++it)
cout<<"List contains "<<*it<<"\n";
return 0;
}

(Try this in NetRun now!)

This prints out the contents of the list, one at a time.

Lists support a surprising range of features.  Here are some of the more surprising features:
Lists are definitely something to keep in your toolbox!