sysprog 9
TRANSCRIPT
C/C++ For Linux
Session 9C++ - Session 4
Outline
● Templates● STL session 1
– Containers and iterators
The Problem
● Decoupling type-independent and type-dependent data– Consider containers
● Generic programming– Consider algorithms
● Still preserve safe typing– As opposed to void *
Templates
● Syntax● Parameters● Specialization● Function Templates
Template Specialization
● Order: More -> Less● Compile time● Default parameters● GNU
– Include– Compilation Performance
● Readability– Code
– Compiler messages
Type ID
● reinterpret_cast: bitwise● static_cast: some relation● const_cast: remove const● dynamic_cast: dynamic data
– Better type checking– More expensive
● typeid operator– type_info::name()
Standard Template Library
● Containers & Iterators● Algorithms & Functionals● Strings & Streams● std namespace● STL Manual: http://www.sgi.com/tech/stl/
Containers
● Holds other objects● Design Problem:
– Generic types held (don't care element)
– Some commonality in iface (don't care container)● Iterating● Algorithms
– Some specifics in iface– Efficiency
STL Solution
● Templates for generic types● Iterators to decouple iteration● Adapters for interface adjustments● Functors to decouple algorithm operations from
obj/contner code.
Iterators
● Points to position of element● Operators for element access
– “Dereference” *
– Access ->
– Move positions ++, --
– Equality ==
– Assignment =
Functors
● Function object● Binary and unary functors● Predicates● Adapters● Algorithms
Common Container Interface
● iterator, const_iterator, reverse_iterator● begin(), end(), rbegin(), rend()● push_back(), back(), pop_back()● insert, erase, clear● size(), empty()● Template Parameters
– Element Type, Allocator
Vector
● Fast access, expensive resize● Access: [], at()● reserve()/resize()● max_size()● Ctors: range, size
List
● Expensive access, quick resize● push_front(), front(), pop_front● splice(), merge(), sort()
Deque
● Double ended queue● Front methods from list● Also parameterized by compare● [] from vector
Sequence Adapters
● Parameterized by Container● queue● priority_queue● stack
Associative Containers
● Unique– Pair, map, hash_map, set
● Multiple– Multimap, multiset, hash_multimap
Map/Multimap
● <Key, Value, Allocator, Cmp>● [“key”], find● Pairs● lower_bound● upper_bound● equal_range
Additional
● set/multiset: – always sorted
– No Value
● hash_map/hash_multimap– Hash parameter