2003 Prentice Hall, Inc. All Rights Reserved
2003 Prentice Hall, Inc. All Rights Reserved
• Sequence containers
– vector
– deque
– list
• Associative containers
– set
– multiset
– map
– multimap
• Container adapters
– stack
– queue
– priority_queue
• Usage
– std::istream_iterator< int > inputInt( cin )
• Can read input from cin
• *inputInt
– Dereference to read first int from cin
• ++inputInt
– Go to next int in stream
– std::ostream_iterator< int > outputInt(cout)
• Can output ints to cout
• *outputInt = 7
– Outputs 7 to cout
• ++outputInt
– Advances iterator so we can output next int
• Input
– Read elements from container, can only move forward
• Output
– Write elements to container, only forward
• Forward
– Combines input and output, retains position
– Multi-pass (can pass through sequence twice)
• Bidirectional
– Like forward, but can move backwards as well
• Random access
– Like bidirectional, but can also jump to any element
• Sequence containers
– vector: random access
– deque: random access
– list: bidirectional
• Associative containers (all bidirectional)
– set
– multiset
– Map
– multimap
• Container adapters (no iterators supported)
– stack
– queue
– priority_queue
• All
– ++p, p++
• Input iterators
– *p
– p = p1
– p == p1, p != p1
• Output iterators
– *p
– p = p1
• Forward iterators
– Have functionality of input and output iterators
• Bidirectional
– --p, p--
• Random access
– p + i, p += i
– p - i, p -= i
– p[i]
– p < p1, p <= p1
– p > p1, p >= p1
• vector
– <vector>
– Data structure with contiguous memory locations
• Access elements with []
– Use when data must be sorted and easily accessible
• When memory exhausted
– Allocates larger, contiguous area of memory
– Copies itself there
– Deallocates old memory
• Has random access iterators
• Declarations
– std::vector <type> v;
• type: int, float, etc.
• Iterators
– std::vector<type>::const_iterator iterVar;
• const_iterator cannot modify elements
– std::vector<type>::reverse_iterator iterVar;
• Visits elements in reverse order (end to beginning)
• Use rbegin to get starting point
• Use rend to get ending point
• vector functions
– v.push_back(value)
• Add element to end (found in all sequence containers).
– v.size()
• Current size of vector
– v.capacity()
• How much vector can hold before reallocating memory
• Reallocation doubles size
– vector<type> v(a, a + SIZE)
• Creates vector v with elements from array a up to (not including)
a + SIZE
• vector functions
– v.insert(iterator, value )
• Inserts value before location of iterator
– v.insert(iterator, array , array + SIZE)
• Inserts array elements (up to, but not including array + SIZE) into
vector
– v.erase( iterator )
• Remove element from container
– v.erase( iter1, iter2 )
• Remove elements starting from iter1 and up to (not including)
iter2
– v.clear()
• Erases entire container
• ostream_iterator
– std::ostream_iterator< type >
Name( outputStream, separator );
• type: outputs values of a certain type
• outputStream: iterator output location
• separator: character separating outputs
• Example
– std::ostream_iterator< int > output( cout, " " );
– std::copy( iterator1, iterator2, output );
• Copies elements from iterator1 up to (not including)
iterator2 to output, an ostream_iterator
• list container
– Header <list>
– Efficient insertion/deletion anywhere in container
– Doubly-linked list (two pointers per node)
– Bidirectional iterators
– std::list< type > name;
• list functions
– t.swap(otherObject);
• Exchange contents
– t.assign(iterator1, iterator2)
• Replaces contents with elements in range of iterators
– t.remove(value)
• Erases all instances of value
• Associative containers
– Direct access to store/retrieve elements
– Uses keys (search keys)
– 4 types: multiset, set, multimap and map
• Keys in sorted order
• multiset and multimap allow duplicate keys
• multimap and map have keys and associated values
• multiset and set only have values
• multiset
– Header <set>
– Fast storage, retrieval of keys (no values)
– Allows duplicates
– Bidirectional iterators
• Ordering of elements
– Done by comparator function object
• Used when creating multiset
– For integer multiset
• less<int> comparator function object
• multiset< int, std::less<int> > myObject;
• Elements will be sorted in ascending order
• Multiset functions
– ms.insert(value)
• Inserts value into multiset
– ms.count(value)
• Returns number of occurrences of value
– ms.find(value)
• Returns iterator to first instance of value
– ms.lower_bound(value)
• Returns iterator to first location of value
– ms.upper_bound(value)
• Returns iterator to location after last occurrence of value
• Class pair
– Manipulate pairs of values
– Pair objects contain first and second
• const_iterators
– For a pair object q
q = ms.equal_range(value)
• Sets first and second to lower_bound and
upper_bound for a given value
• set
– Header <set>
– Implementation identical to multiset
– Unique keys
• Duplicates ignored and not inserted
– Supports bidirectional iterators (but not random access)
– std::set< type, std::less<type> > name;
• multimap
– Header <map>
– Fast storage and retrieval of keys and associated values
• Has key/value pairs
– Duplicate keys allowed (multiple values for a single key)
• One-to-many relationship
• I.e., one student can take many courses
– Insert pair objects (with a key and value)
– Bidirectional iterators
• Example
std::multimap< int, double, std::less< int > > mmapObject;
– Key type int
– Value type double
– Sorted in ascending order
• Use typedef to simplify code
• map
– Header <map>
– Like multimap, but only unique key/value pairs
• One-to-one mapping (duplicates ignored)
– Use [] to access values
– Example: for map object m
m[30] = 4000.21;
• Sets the value of key 30 to 4000.21
– If subscript not in map, creates new key/value pair
• Type declaration
– std::map< int, double, std::less< int > >;
• Container adapters
– stack, queue and priority_queue
– Not first class containers
• Do not support iterators
• Do not provide actual data structure
– Programmer can select implementation
– Member functions push and pop
• stack
– Header <stack>
– Insertions and deletions at one end
– Last-in, first-out (LIFO) data structure
– Can use vector, list, or deque (default)
– Declarations
stack<type, vector<type> > myStack;
stack<type, list<type> > myOtherStack;
stack<type> anotherStack; // default deque
• vector, list
– Implementation of stack (default deque)
– Does not change behavior, just performance (deque and
vector fastest)
• queue
– Header <queue>
– Insertions at back, deletions at front
– First-in-first-out (FIFO) data structure
– Implemented with list or deque (default)
• std::queue<double> values;
• Functions
– push( element )
• Same as push_back, add to end
– pop( element )
• Implemented with pop_front, remove from front
– empty()
– size()
• priority_queue
– Header <queue>
– Insertions happen in sorted order, deletions from front
– Implemented with vector (default) or deque
– Highest priority element always removed first
• Heapsort algorithm puts largest elements at front
• less<T> default, programmer can specify other comparator
– Functions
• push(value), pop(value)
• top()
– View top element
• size()
• empty()
21.5 Algorithms
• Before STL
– Class libraries incompatible among vendors
– Algorithms built into container classes
• STL separates containers and algorithms
– Easier to add new algorithms
– More efficient, avoids virtual function calls
– <algorithm>
• random_shuffle(iter1, iter2)
– Randomly mixes elements in range
• count(iter1, iter2, value)
– Returns number of instances of value in range
• count_if(iter1, iter2, function)
– Counts number of instances that return true
• min_element(iter1, iter2)
– Returns iterator to smallest element
• max_element(iter1, iter2)
– Returns iterator to largest element
• accumulate(iter1, iter2)
– Returns sum of elements in range
• for_each(iter1, iter2, function)
– Calls function on every element in range
– Does not modify element
• transform(iter1, iter2, iter3, function)
– Calls function for all elements in range of iter1-iter2,
copies result to iter3
• swap(element1, element2)
– Exchanges two values
– swap( a[ 0 ], a[ 1 ] );
• iter_swap(iter1, iter2)
– Exchanges the values to which the iterators refer
Vector v1 contains: 1 3 5 7 9
Vector v2 contains: 2 4 5 7 9
After copy_backward, results contains: 1 3 5 7 9
After merge of v1 and v2 results2 contains:
1 2 3 4 5 5 7 7 9 9
After unique results2 contains:
1 2 3 4 5 7 9
Vector v1 after reverse: 9 7 5 3 1
• set_symmetric_difference(iter1, iter2,
iter3, iter4, iter5)
– Copies elements in set (1-2) but not set (3-4), and vice versa, into
iter5
• a1: 1 2 3 4 5 6 7 8 9 10
• a2: 4 5 6 7 8
• set_symmetric_difference: 1 2 3 9 10
– Both sets must be sorted
21.5.12 Heapsort
21.5.12 Heapsort
• Functions
– push_heap(iter1, iter2)
• The iterators must specify a heap
• Adds last element in object to heap
– Assumes other elements already in heap order
– pop_heap(iter1, iter2)
• Removes the top element of a heap and puts it at the end of the
container.
• Function checks that all other elements still in a heap
• Range of the iterators must be a heap.
• If all the elements popped, sorted list
• min(value1, value2)
– Returns smaller element
• max(value1, value2)
– Returns larger element
• adjacent_difference
• inner_product
• partial_sum
• nth_element
• partition
• stable_partition
• next_permutation
• prev_permutation
• rotate
• rotate_copy
• adjacent_find
• partial_sort
• partial_sort_copy
• stable_sort
• Class bitset
– Represents a set of bit flags
– Can manipulate bit sets
• Operations
– bitset <size> b; create bitset
– b.set( bitNumber) set bit bitNumber to on
– b.set() all bits on
– b.reset(bitNumber) set bit bitNumber to off
– b.reset() all bits off
– b.flip(bitNumber) flip bit (on to off, off to on)
– b.flip() flip all bits
– b[bitNumber] returns reference to bit
– b.at(bitNumber) range checking, returns reference
• Operations
• b.test(bitNumber) has range checking; if bit on, returns true
• b.size() size of bitset
• b.count() number of bits set to on
• b.any() true if any bits are on
• b.none() true if no bits are on
• can use &=, |=, !=, <<=, >>=
– b &= b1
– Logical AND between b and b1, result in b
• b.to_string() convert to string
• b.to_ulong() convert to long
vector v contains:
1 2 3 4 5 6 7 8 9 10
Sum of squares of elements in integers using binary
function sumSquares: 385
Sum of squares of elements in integers using binary
function object of type SumSquaresClass< int >: 385