160 likes | 279 Views
Standard Template Library. Homework. List HW will be posted on webpage Due Nov 15. The STL includes:. Containers – a data structure which holds arbitrary data type Iterators – way of ‘browsing’ through a container
E N D
Homework • List HW will be posted on webpage • Due Nov 15
The STL includes: • Containers – a data structure which holds arbitrary data type • Iterators – way of ‘browsing’ through a container • Algorithms – operations which can be performed on any container (where it makes sense)
Containers • vector • list • deque (double-ended queue) • set and multiset • map and multimap
vector • Much like an array • Accessible with [] • Provides constant-time random access • Dynamically resizable • May be of any type.
list • Changes size as elements are inserted or deleted • May be of any type.
list syntax #include <list> using namespace std; void aFunc() { list<float> lst; lst.push_back(7.0); }
Some list methods • Since list is a class, it has methods • push_back() • pop_back() • front() • back() • empty() • clear() • size() • resize() • capacity() • See www.sgi.com/tech/stl/list.html
Iterator • Iterators are a convenient way to ‘browse’ • Every container offers a object.start() • Every container offers an object.end() • Every iterator supports ++ and - - (no matter what the structure of the container)
List organization • From any car in the train you may go to the preceding or succeeding one • Use ++ or - - operation on the iterator
Lists • #include <list> • A list is like a freight train • Cars in sequence, starting with 0 • Each car is a container for a type of data – e.g. an int, a float, a object
Examine the elements of a list #include <list> using namespace std; int main() { list<float> lst; list<float>::iterator lp; for (lp = lst.begin(); lp != lst.end(); ++lp) { // do something here } return 0; }
Algorithms • You must include the header #include <algorithm> using namespace std;
Algorithms • Provides standard algorithms like sort and swap on any kind of data in the container, provided …
Algorithms • Provides standard algorithms like sort and swap on any kind of data in the container, provided … • That prerequisites are defined (the < operator for sort)
Sort algorithm example #include <list> #include <algorithm> #include <iostream> using namespace std; int main() { list<int> lst; for (int i = 0; i < 5; ++i) { int aNum = rand() % 100; lst.push_back(aNum); } lst.sort(); return 0; }