Standard Template Library
Programming paradigm: generic
programming
the decomposition of programs into components which may be developed separately and combined arbitrarily, subject only to well-defined interfaces. lots of orthogonality
Components
Containers Iterators Algorithms
Example 1
// Simple STL vector program from Ira Pohl, UC Santa Cruz #include
#include using namespace std; int main () { vector v(100); // 100 is vector's size for (int i = 0; i < 100; ++i) v[i] = i; for (vector::iterator p = v.begin(); p != v.end(); ++p) cout << *p << '\t'; cout << endl; }
Example 2
#include #include // list container #include // for accumulate using namespace std; // Using the list container int main() { double w[4] = { 0.9, 0.8, 88, -99.99 }; list z; for (int i = 0; i < 4; ++i) z.push_front(w[i]); print(z); z.sort(); print(z); cout << "sum is " << accumulate(z.begin(), z.end(), 0.0) << endl; }
Containers
Sequential – ordered by sequence
Vector – dynamic array List – linked list Deque – double-ended queue
Sets – stores unique keys Multisets – allows multiple copies of key Maps – associates unique keys and values Multimaps – allows multiple copies of key
Associative – use keys for ordering
Common container interfaces
Constructors Element access Element insertion Element deletion Destructor Iterators
Useful definitions and members
CON::iterator CON::value_type c.begin() c.end() c.size() c.empty()
Useful sequence members
c.insert(w_it, v) – inserts v before w_it c.insert(w_it,v,n) – inserts n copies of v before w_it c.insert(w_it,b_it,e_it) – inserts b_it to e_it before w_it c.erase(w_it) – erases element at w_it c.erase(b_it,e_it) – erases b_it to e_it
Useful Associative Container Definitions, Members
ASSOC::key_type c.find(k) – returns iterator to element with key k or c.end() c.count(k) – returns number of elements with key k
Example 3 - Map
//Associative Containers - looking up ages #include #include