STL – Standard Template Library Linked Lists
Container Class Philosophy • Container classes hold something. • As well as the container, there are ITERATORS • Iterators perform the function of telling where something is. • Such as pointers, subscripts, etc. • Iterators are also a class but it travels with the container class. They need each other and each is not useful without the other.
Iterator Philosophy • Giving a pointer to the user gives them way too much power. • Can get to the data in a class in an uncontrolled way. • The reason data is typically private is to control the access to it (so it meets needed criteria). • The iterator class gives the user a controlled access to a “pointer” to an individual item in the container object.
Sidebar – Lvalue & Rvalue • Look at: • X=Y; • Y=X; • Have different meaning • Now look at: • X=Y*3+6; • Y*3+6=X; • Cannot be done • What is on the left is not the same as what can be on the right.
Lvalue and Rvalue • When we do x=y; we think of the memory position of x (not the value of x), whereas we think of the value of y being placed into the memory location x. • So an lvalue is something that can be used on the left side of an assignment (refers to a memory location). • An rvalue can be used on the right side (the actual value). • The variable x has an lvalue and a rvalue, but y*3+6 only has an rvalue.
Lvaue and Rvalue and Functions • All lvalues can also be rvalues (but not the reverse). • You have had more experience with functions returning rvalues. • A function can return an lvalue (which can be used as an lvalue or an rvalue). • To return the value as an lvalue use & in the return data type and return &location.
Linked List in the STL • The STL implements a doubly linked list. • int size() const • void clear(); • bool empty(); • void push_back(const OBJECT & x); • void pop_back(); • const object & back () const; • object & back (); not really good • const object & front () const; • void push_front (const object & x); • void pop_front();
Linked List Iterators • To get a linked list use: • #include <list> • And in main: • list <dtype> X; • To get a linked list iterator • list<dtype>::iterator X_iter;
Iterator Operations iterator begin(); iterator end(); // iterator to AFTER the last itr++; ++itr; itr--; --itr; itr1==itr2; itr1!=itr2; *itr