610 likes | 869 Views
Standard Template Library. There are 3 key components in the STL Containers Iterators Algorithms Promote reuse More debugged May be more efficient. Containers. There are 3 types of containers Sequence containers Associative containers Container adapters
E N D
Standard Template Library • There are 3 key components in the STL • Containers • Iterators • Algorithms • Promote reuse • More debugged • May be more efficient
Containers • There are 3 types of containers • Sequence containers • Associative containers • Container adapters • Sequence and Associative containers are first class containers • There are 4 near containers • C-like arrays • String • Bitset • Valarray – high speed math
Container Classes • Sequence Containers – just hold values. • vector – 1D 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 • Associate values • set – rapid lookup – no duplicates • multiset – rapid lookup – duplicates allowed • map – one to one mapping, no duplicates, rapid key lookup • multimap – one to many mapping, duplicates allowed, rapid key based lookup
Container Adapters • These implement data structures that can be implemented with different containers • stack – last in first out – can be implemented with a vector, deque or a list. • queue – first in first out • priority_queue – highest priority is the first one out.
Member functions for all containers • Default constructor – default initialization. There may be a variety of constructors for various initialization methods. • Copy constructor – initializes a container to be a copy of the existing container. • Destructor • empty – returns true or false • max_size – returns max size
More member functions • size – returns the current size • operator= - assigns one container to another • operator< - returns true or false • operator<=, >, >=, ==, != • swap – swap the elements of 2 containers.
First class member functions • 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 • Many implementations of the STL are different than normal libraries • Some use the following method (using the vector class). #include <vector> using namespace std; • Notice, no .h in the file name. • Some implementations may work with the .h and no using.
The STL header files • The header files are in • <vector> • <list> • <deque> • <queue> • <stack> • <map> • <set> • <bitset>
Typedefs • 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 • const_iterator – • reverse_iterator – for going backwards in the container • const_reverse_iterator • difference_type – the type of the result of subtracting 2 iterators to the same container. • size_type – the type used to count items in a container and index through a sequence container
Iterators • Iterators are a lot like pointers. They tell where something is. • An Iterator is implemented as a class • This prevents many errors • 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 • 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 • vector – random and above • deque – random and above • list – bi-directional and above • set – bi-directional and above • multiset – bi-directional and above • map – bi-directional and above • multimap – bi-directional and above • stack – none • queue – none • priority_queue – none
Iterator Operations • The following are for all iterator types • ++p – preincrement • p++ - postincrement • Input iterators • *p – dereference an iterator for an rvalue • p=p1 – assign iterators • p==p1 – compare for equality • p!=p1 – compare for inequality • Output iterators • *p – dereference for use as lvalue • p=p1 – assign iterators
More iterator operators • Forward operators • Same as input and output • Bi-directional iterators • --p – predecrement • p-- - postdecrement • 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<p1 – true if p is before p1 • p>p1, p>=p1, p<=p1
Algorithms • Algorithms are generic functions that work across all the containers. • They are not member functions of a container class. • This way the algorithms can be written without being rewritten for each class. • Many algorithms work on a sequence by being sent a begin and end iterator.
Numerical Algorithms • Need to use header <numeric> • accumulate() • inner_product() • partial_sum() • adjacent_difference()
Tips part 1 • For any particular application, several different STL containers could be appropriate. Select the most appropriate container that achieves the best performance for that application. • 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 • The STL approach allows general programs to be written so the code does not depend on the underlying container. • STL avoids inheritance to achieve best run time performance. • Know STL components. Choose the most appropriate container for your application. • Attempting to dereference an iterator outside the container is an error. In particular, dereferencing end() will be an error.
Tips part 3 • STL is extensible. It is straightforward to add new algorithms and to do so without changes to STL containers. • STL algorithms can operate on STL containers and on pointer based C-like arrays. • Since STL algorithms process many containers through iterators, one algorithm can often be used with many containers.
Tips, part 4 • Applications that require frequent insertions and deletions at both ends of a container normally use a deque rather than a vector. • Applications with frequent insertions and deletions in the middle of a container normally use a list. • The vector container is best for random access. • It is faster to insert many items at once than one at a time.
Sequence containers • Vector and deque are based on arrays. • List is a linked list data structure. • 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. • Vector subscripting does not perform range checking. Use the member function at.
Sequence Container Operations • The sequence containers also have the operations • push_back – insert at the end • pop_back – remove from the end
The vector Sequence Container • Uses contiguous memory locations • Supports random access iterators • Can use all the iterator functions • 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 p1; for (p1=v.begin(); p1!=v.end(); p1++) cout << *p1; vector<int>::reverse_iterator p2; for (p2=v.rbegin(); p2 != v.rend(); p2++) cout<<*p2; }
Vector functions • 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). • copy(a.begin(), a.end(), v.begin()); • Remember, front and back cannot be used on an empty vector.
Addressing • 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 • myl.push_front(value); • myl.pop_front(value); • myl.splice(myl_pos, otherlist); • Remove elements in otherlist and put before myl_pos in myl • myl.splice(myl_pos, otherlist, other_pos); // move 1 element • myl.splice(myl_pos, otherlist, other_start, other_end);
More List Operations • myl.remove(myl_pos); • myl.sort(); • myl.sort(bool cmp(type, type)); • Sort using a comparison function (needed for list of records). • myl.unique(); • Remove duplicates in a sorted list. • Need bool function for equality if not using the default. • myl.merge(other); • Takes 2 sorted lists and merges them • Can add a bool function for merge condition.
Last of List operations • myl.reverse(); • myl.swap(other); • Swaps the entire container • myl.assign(other_start, other_end); • Make myl contain only part of other.
Deque Operations • Has basically the same functions as vector • Additionally there are • push_front • pop_front
Associative classes • These containers are key oriented • Set and multiset just have a key; set is for unique values, and multiset allows duplicate values. • Map and multimap have a record associated with each key. • All associative containers can • find • lower_bound • upper_bound • count
Multiset • There are built in comparison templated functions less<type> and greater<type> • Need to have < and > defined on the type. • Kept in order • The order is determined by a comparator function object given during creation. • Supports bidirectional iterators • Uses a somewhat balanced tree to implement
Operations • Must use the include file <set> • Contains both the set and multiset classes • Constructor • multiset<keytype, cmp<type> > • cmp is less or greater • insert(value) • int count(value) – how many of value are in the multiset (not used in set). • 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. • The pair class • pair<type1, type2> pobj; • This is a class to hold 2 values. • Data is public • pobj.first and pobj.second • pair equal_range(value) – returns an iterator pair pointing to the beginning and end of the range containing the single value • pair<multiset<int>::iterator, multiset<int>::iterator> p; • p=myset.equal_range(37);
Set • No duplicates • The insert function returns an iterator, bool pair. • If the insert worked (not a duplicate), the bool is true and the iterator points to where it was inserted. • If the insert failed (tried to insert a duplicate), bool is false and the iterator value is unimportant.
Multimap • Use the header <map> for both map and multimap. • Methods: • multimap<keytype, recordtype, cmp> mobj; • int count(keyvalue) • void insert(pair) • multimap<type1, type2, cmp>::value_type(v1, v2) • Creates a pair with v1 and v2 • iterators point to a pair • itr->first • itr->second
Map • Same functions and idea as multimap, just no duplicates. • Can use mobj[key] • This is not a subscript • It returns a reference to a position (who knows where) associated with that key. • You can place values there or use the values from there.
Stack Adapter • Implemented with a vector, list or deque (default). • void push(value) • void pop() • type top() • bool empty() • int size() • stack<type, vector<type> >stk; • stack<type> stk;
Queue Adaptor • Implemented with a list or a deque (default). • push – add to back • pop – remove from front • front – get first value • back – get last value • empty – size
Priority Queue • Implemented with a deque or vector (default). • Uses a heap principle • push • pop • top • empty • Size
Algorithms • fill(iter_start, iter_end, value) • Fill the container from start to end with value. • fill_n(iter_start, count, value) • Fill the container with count copies of value starting at start. • generate(start, end, function) • Function returns value of type, takes no arg. Places return value in container. Called several times. • generate_n(start, count, function)
More Algorithms • bool equal(start1, end1, start2) • Returns true if all values between start and end of container1 are the same as the corresponding values in container2. • bool equal(start1, end1, start2, func) • Func is an equality boolean function that takes 2 args of type. • pair<iter, iter> mismatch(s1, e1,s2) • Returns a pair of iterators for the first case of a value in container1 not equal to the corresponding value in container2. • pair<> mismatch(s1, e1,s2, func)
Algorithms again • bool lexicographical_compare(s1,e1,s2 , e2) • Used mainly with strings. Returns true if the first container is less than second lexicographically. • remove(s,e,value) • Remove all occurances of value between s and e. • remove_copy(s1,e1,s2,value) • s2 has a copy of s1 with instances of value removed • remove_if(s,e,bool_func) • Removes the value when bool_func is true • Remove_copy_if(s1,e1,s2, bool_func)
Even More • replace(s,e,old_value,new_value) • replace_if(s,e, bool_func, new) • Replaces value with new if old passed to bool_func returns true. • replace_copy(s1,e1,s2, old,new) • Makes a copy of the container with instances of old value replaced with new value. • replace_copy_if(s1,e1,s2, bool_func,new)
Math type functions • random_shuffle(begin, end) • Change the order of items between begin and end. • count(begin, end, value) • Give a count of items with value • count_if(begin, end, bool_func) • min_element(begin, end) • max_element(begin, end) • Min and max return iterators.