Standard Template Library n There are 3 key

Standard Template Library n There are 3 key components in the STL – Containers – Iterators – Algorithms n Promote reuse n More debugged n May be more efficient

Containers n There are 3 types of containers – Sequence containers – Associative containers – Container adapters n Sequence and Associative containers are first class containers n There are 4 near containers – C-like arrays – String – Bitset – Valarray – high speed math

Container Classes n Sequence Containers – just hold values. – vector – 1 D array – rapid insertions and deletions at back – direct access to elements – deque – rapid insertions and deletions at front or back – direct access to any element – list – doubly linked list – rapid insertions and deletions anywhere

Associative Containers n Associate values n set – rapid lookup – no duplicates n multiset – rapid lookup – duplicates allowed n map – one to one mapping, no duplicates, rapid key lookup n multimap – one to many mapping, duplicates allowed, rapid key based lookup

Container Adapters n These implement data structures that can be implemented with different containers n stack – last in first out – can be implemented with a vector, deque or a list. n queue – first in first out n priority_queue – highest priority is the first one out.

Member functions for all containers n Default constructor – default initialization. There may be a variety of constructors for various initialization methods. n Copy constructor – initializes a container to be a copy of the existing container. n Destructor n empty – returns true or false n max_size – returns max size

More member functions n size – returns the current size n operator= - assigns one container to another n operator< - returns true or false n operator<=, >, >=, ==, != n swap – swap the elements of 2 containers.

First class member functions n n n n These are only available to first class containers (sequence and associative) begin – return an iterator that refers to the first element of the container. end – return an iterator that refers to the position after the end of the container rbegin – return a reverse_iterator that refers to the last element of the container rend - return a reverse_iterator that refers to the position before the first element of the container erase – erases one or more elements clear – erases all elements from the container.

Using the STL n Many implementations of the STL are different than normal libraries n Some use the following method (using the vector class). #include <vector> using namespace std; n Notice, no. h in the file name. n Some implementations may work with the. h and no using.

The STL header files n The header files are in – <vector> – <list> – <deque> – <queue> – <stack> – <map> – <set> – <bitset>

Typedefs n The following are typedefs defined in the first class containers. – value_type – the type of element stored in the container – reference – a reference to the type of element stored in the container – const_reference – reference that cannot change the contents of the container – pointer – a pointer to the type of element stored in the container – iterator – an iterator type to the element

More typedefs n const_iterator – n reverse_iterator – for going backwards in the container n const_reverse_iterator n difference_type – the type of the result of subtracting 2 iterators to the same container. n size_type – the type used to count items in a container and index through a sequence container

Iterators n Iterators are a lot like pointers. They tell where something is. n An Iterator is implemented as a class n This prevents many errors n Allows as many iterators as you want for a class in both the implementation of the class and the using of the class

Iterator Categories n n n Input – used to read an element from a container. Can only move forward. Can only go through the sequence once. Output – used to write an element to a container. Can only move forward. Only one pass. Forward – combines input and output and retain position in container Bi-directional – combines input and output and allows backward movement. Can have more than one pass. Random access – can jump to any element.

Iterators supported n vector – random and above n deque – random and above n list – bi-directional and above n set – bi-directional and above n multiset – bi-directional and above n map – bi-directional and above n multimap – bi-directional and above n stack – none n queue – none n priority_queue – none

Iterator Operations n The following are for all iterator types – ++p – preincrement – p++ - postincrement n Input iterators – *p – dereference an iterator for an rvalue – p=p 1 – assign iterators – p==p 1 – compare for equality – p!=p 1 – compare for inequality n Output iterators – *p – dereference for use as lvalue – p=p 1 – assign iterators

More iterator operators n Forward operators – Same as input and output n Bi-directional iterators – --p – predecrement – p-- - postdecrement n Random-Access iterators – – – p+=i – increment p by i positions p-=i – decrement p by i positions p+i – p incremented by i positions p-i p[i] – return a reference to the element offset from p by i positions – p<p 1 – true if p is before p 1 – p>p 1, p>=p 1, p<=p 1

Algorithms n Algorithms are generic functions that work across all the containers. n They are not member functions of a container class. n This way the algorithms can be written without being rewritten for each class. n Many algorithms work on a sequence by being sent a begin and end iterator.

Mutating sequence algorithms copy() transform() unique_copy() copy_backward() generate() unique() generate_n() swap_ranges() rotate() remove_copy() remove_copy_if() replace() reverse() replace_copy_if() reverse_copy() fill() partition() rotate_copy() stable_partition() swap() iter_swap() replace_copy() remove_if() fill_n() replace_if() random_shuffle()

Non Mutating sequence alg. adjacent-find() count_if() equal() find() for_each() mismatch() search_n()

Numerical Algorithms n Need to use header <numeric> – accumulate() – inner_product() – partial_sum() – adjacent_difference()

Tips part 1 n For any particular application, several different STL containers could be appropriate. Select the most appropriate container that achieves the best performance for that application. n STL capabilities are implemented to operate efficiently across a wide variety of applications. You may need to write your own customized implementations for specialized applications.

Tips part 2 n The STL approach allows general programs to be written so the code does not depend on the underlying container. n STL avoids inheritance to achieve best run time performance. n Know STL components. Choose the most appropriate container for your application. n Attempting to dereference an iterator outside the container is an error. In particular, dereferencing end() will be an error.

Tips part 3 n STL is extensible. It is straightforward to add new algorithms and to do so without changes to STL containers. n STL algorithms can operate on STL containers and on pointer based C-like arrays. n Since STL algorithms process many containers through iterators, one algorithm can often be used with many containers.

Tips, part 4 n Applications that require frequent insertions and deletions at both ends of a container normally use a deque rather than a vector. n Applications with frequent insertions and deletions in the middle of a container normally use a list. n The vector container is best for random access. n It is faster to insert many items at once than one at a time.

Sequence containers n Vector and deque are based on arrays. n List is a linked list data structure. n Vector is a smart array. It can change size dynamically. When a vector needs more space, it reallocates an array of twice the size and copies the old contents into the new array. Can do vector assignment. n Vector subscripting does not perform range checking. Use the member function at.

Sequence Container Operations n The sequence containers also have the operations – push_back – insert at the end – pop_back – remove from the end

The vector Sequence Container n Uses contiguous memory locations n Supports random access iterators – Can use all the iterator functions n All STL algorithms can operate on a vector.

Code with vector #include<vector> using namespace std; void main() { vector<int> v; v. push_back(2); v. push_back(3); v. push_back(4); cout<<v. size()<<v. capacity()<<endl; vector<int>: : const_iterator p 1; for (p 1=v. begin(); p 1!=v. end(); p 1++) cout << *p 1; vector<int>: : reverse_iterator p 2; for (p 2=v. rbegin(); p 2 != v. rend(); p 2++) cout<<*p 2; }

Vector functions n Copy Constructor – vector<type> v(a, a+SIZE); – Creates v with a copy of a (which is a vector or c-type array) from beginning (a) to the end (a+SIZE, the one at a+SIZE is not copied). n copy(a. begin(), a. end(), v. begin()); n Remember, front and back cannot be used on an empty vector.

Addressing n n n n n There are several ways to address an element of a vector. v[i]=value; v. at(i)=value; //subscript checking v. insert(v. begin()+i, value); // moves rest v. insert(pos, otherstart, otherend); v. erase(v. begin()+i); v. erase(begin, end); v. clear(); //erases all If the element is a pointer, the erase does not delete the element.

List Operations n myl. push_front(value); n myl. pop_front(value); n myl. splice(myl_pos, otherlist); – Remove elements in otherlist and put before myl_pos in myl. splice(myl_pos, otherlist, other_pos); // move 1 element n myl. splice(myl_pos, otherlist, other_start, other_end);

More List Operations myl. remove(myl_pos); n myl. sort(bool cmp(type, type)); n – Sort using a comparison function (needed for list of records). n myl. unique(); – Remove duplicates in a sorted list. – Need bool function for equality if not using the default. n myl. merge(other); – Takes 2 sorted lists and merges them – Can add a bool function for merge condition.

Last of List operations n myl. reverse(); n myl. swap(other); – Swaps the entire container n myl. assign(other_start, other_end); – Make myl contain only part of other.

Deque Operations n Has basically the same functions as vector n Additionally there are – push_front – pop_front

Associative classes n These containers are key oriented n Set and multiset just have a key; set is for unique values, and multiset allows duplicate values. n Map and multimap have a record associated with each key. n All associative containers can – find – lower_bound – upper_bound – count

Multiset n There are built in comparison templated functions less<type> and greater<type> n Need to have < and > defined on the type. n Kept in order n The order is determined by a comparator function object given during creation. n Supports bidirectional iterators n Uses a somewhat balanced tree to implement

Operations n Must use the include file <set> – Contains both the set and multiset classes n Constructor n multiset<keytype, cmp<type> > – cmp is less or greater n insert(value) n int count(value) – how many of value are in the multiset (not used in set). n iterator find(value) – gives an iterator to the value if found – returns end() if not found.

More Methods void insert(arraystart, arrayend) – adds many values to the multiset. n The pair class n – – pair<type 1, type 2> pobj; This is a class to hold 2 values. Data is public pobj. first and pobj. second n pair equal_range(value) – returns an iterator pair pointing to the beginning and end of the range containing the single value n pair<multiset<int>: : iterator, multiset<int>: : iterator> p; n p=myset. equal_range(37);

Set n No duplicates n The insert function returns an iterator, bool pair. n If the insert worked (not a duplicate), the bool is true and the iterator points to where it was inserted. n If the insert failed (tried to insert a duplicate), bool is false and the iterator value is unimportant.

Multimap n Use the header <map> for both map and multimap. n Methods: – multimap<keytype, recordtype, cmp> mobj; – int count(keyvalue) – void insert(pair) – multimap<type 1, type 2, cmp>: : value_type(v 1, v 2) • Creates a pair with v 1 and v 2 – iterators point to a pair • itr->first • itr->second

Map n Same functions and idea as multimap, just no duplicates. n Can use mobj[key] n This is not a subscript n It returns a reference to a position (who knows where) associated with that key. n You can place values there or use the values from there.

Stack Adapter n Implemented with a vector, list or deque (default). n void push(value) n void pop() n type top() n bool empty() n int size() n stack<type, vector<type> >stk; n stack<type> stk;

Queue Adaptor n Implemented with a list or a deque (default). n push – add to back n pop – remove from front n front – get first value n back – get last value n empty – size

Priority Queue n Implemented with a deque or vector (default). n Uses a heap principle n push n pop n top n empty n Size

Algorithms n fill(iter_start, iter_end, value) – Fill the container from start to end with value. n fill_n(iter_start, count, value) – Fill the container with count copies of value starting at start. n generate(start, end, function) – Function returns value of type, takes no arg. Places return value in container. Called several times. n generate_n(start, count, function)

More Algorithms n bool equal(start 1, end 1, start 2) – Returns true if all values between start and end of container 1 are the same as the corresponding values in container 2. n bool equal(start 1, end 1, start 2, func) – Func is an equality boolean function that takes 2 args of type. n pair<iter, iter> mismatch(s 1, e 1, s 2) – Returns a pair of iterators for the first case of a value in container 1 not equal to the corresponding value in container 2. n pair<> mismatch(s 1, e 1, s 2, func)

Algorithms again n bool lexicographical_compare(s 1, e 1, s 2 , e 2) – Used mainly with strings. Returns true if the first container is less than second lexicographically. n remove(s, e, value) – Remove all occurances of value between s and e. n remove_copy(s 1, e 1, s 2, value) – s 2 has a copy of s 1 with instances of value removed n remove_if(s, e, bool_func) – Removes the value when bool_func is true n Remove_copy_if(s 1, e 1, s 2, bool_func)

Even More n replace(s, e, old_value, new_value) n replace_if(s, e, bool_func, new) – Replaces value with new if old passed to bool_func returns true. n replace_copy(s 1, e 1, s 2, old, new) – Makes a copy of the container with instances of old value replaced with new value. n replace_copy_if(s 1, e 1, s 2, bool_func, new)

Math type functions n random_shuffle(begin, end) – Change the order of items between begin and end. n count(begin, end, value) – Give a count of items with value n count_if(begin, end, bool_func) n min_element(begin, end) n max_element(begin, end) – Min and max return iterators.

More math n accumulate(s, e, start_value) – Adds up values n accumulate(s, e, start_value, func) – func tells how to accumulate (can multiply, etc. ). func takes 2 args, the partial result and the new value. n for_each(s, e, func) – Passes values between s and e to func n transform(s 1, e 1, s 2, func) – Passes each value from s to e to func and places the result in container 2.

Searching n find(s, e, value) – Returns an iterator to the element with value. n find_if(s, e, bool_func) – Returns an iterator to an element that makes bool_func true. n sort(s, e) n bool binary_search(s, e, value)

Swapping n swap(ref, ref) – Takes 2 references and swaps the values n iter_swap(iter, iter) – Takes 2 iterators and swaps the values n swap_ranges(start 1, end 1, start 2) – Swap the elements from start 1 to end 1 with the same number of elements starting at start 2

More algorithms n copy_backward(start 1, end 1, end 2) – Copies from start 1 up to end 1 placing the values starting at end 2 and working backward. Returns iterator positioned at the beginning of the resulting list. n merge(s 1, e 1, s 2, e 2, rstart) – Merge the sorted values from s 1 to e 1 with the sorted values from s 2 to e 2 into the container starting at rstart. Can also have a cmp function for order

Other Algorithms n unique(start, end) – Removes duplicates n unique_copy(s 1, e 1, s 2) n reverse(start, end) – Reverses all the elements n reverse_copy(s 1, e 1, s 2) n inplace_merge(s 1, s 2, e 2) – Merges 2 sorted sequences from the same container back into the same container. Merges from s 1 to s 2 with from s 2 to e 2.

Set Operations n Values must be ordered in container n bool includes(s 1, e 1, s 2, e 2) – Returns true if the set from s 2 to e 2 is contained in the set from s 1 to e 1 n set_difference(s 1, e 1, s 2, e 2, r 1) – Places all the values that are in container 1 but not in container 2 into container r. n set_intersection(s 1, e 1, s 2, e 2, r 1) – Places values that are in both container 1 and container 2 into container r.

Last of set operations n set_symmetric_difference(s 1, e 1, s 2, e 2, r 1) – Place values that are in container 1 but not in container 2 into container r and place values that are in container 2 but not in container 1 into container r. n set_union(s 1, e 1, s 2, e 2, r 1) – Place the union of containers 1 and 2 into container r.

Ranges n lower_bound(s, e, value) – Returns an iterator that gives the first position where value could be inserted in sorted order. n upper_bound(s, e, value) – Returns an iterator that gives the last position where a value could be inserted in sorted order. n equal_range(s, e, value) – Returns a pair of iterators that are the same as calling lower and upper bound

Heapsort n make_heap(s, e) – Makes a heap in the container n sort_heap(s, e) – Sort values that are already in a heap n push_heap(s, e) – Used after a push_back function call. Makes a heap out of what was a heap with one item added.

Last ones n min(value 1, value 2) n max(value 1, value 2)
- Slides: 60