The example:
// list.cc
// Example of use of list
#include <hush/list.h>
#include <iostream.h>
// ALWAYS pass complex value parameters with const& !
void printlist(const list<int>& l)
{
iter<int> listiter = l; // see explanation in main
int* intptr = 0;
while (intptr = listiter())
{
cout << *intptr << " ";
}
cout << endl;
}
int main()
{
list<int> l1; // create an empty list of ints
int i1 = 27, i2 = 3, i3 = 81; // some integers
cout << "length of l1 is " << l1.length() << endl;
// retrieving the length of a list
// insert some elements
l1.insert(&i1); // IMPORTANT: list stores only
// POINTERS to elements, so something
// like l1.insert(3) won't work!
// see the effect of this later on
l1.insert(&i2);
l1.insert(&i3);
cout << "length of l1 is " << l1.length() << endl;
// now we will iterate over the whole list:
iter<int> listiter = l1; // create an iterator for a list, more
// specifically, an iterator for our
// created list
int* intptr = 0; // this POINTER to an integer will
// be used for the iteration
while (intptr = listiter())
{
cout << "item = " << *intptr << endl;
}
cout << "2nd element of l1 = " << *(l1[1]) << endl;
// retrieving an element by index
// an example of datastructure sharing between lists:
list<int> l2 = l1; // creates an alias of l1
printlist(l2);
int* eltptr = l2.head(); // retrieve the first element
*eltptr = 7; // change it
printlist(l2); // of course, l2 has changed, but
printlist(l1); // the elements in l1 have changed too!
// since lists only store POINTERS to elements, the elements that were added
// will be changed:
cout << "i1 is now " << i1 << endl;
// and vice versa:
i2 = 128;
printlist(l1);
// show effect of aliasing:
l1.remove(l1.head()); // remove some elements
l1.remove(l1.head());
printlist(l1); // l1 is a lot shorter
printlist(l2); // l2 changes too
return 0;
}