Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Standard Template Library There are 3 key components in the STL –Containers –Iterators –Algorithms Promote reuse More debugged May be more efficient."— Presentation transcript:

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

2 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

3 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

4 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

5 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.

6 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

7 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.

8 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.

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

10 The STL header files The header files are in –

11 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

12 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

13 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

14 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.

15 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

16 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

17 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

18 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.

19 Mutating sequence algorithms copy()transform()unique_copy()copy_backward() generate()unique()generate_n()swap_ranges() rotate()remove()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()

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

21 Numerical Algorithms Need to use header –accumulate() –inner_product() –partial_sum() –adjacent_difference()

22 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.

23 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.

24 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.

25 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.

26 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.

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

28 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.

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

30 Vector functions Copy Constructor –vector 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.

31 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.

32 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);

33 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.

34 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.

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

36 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

37 Multiset There are built in comparison templated functions less and greater Need to have 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

38 Operations Must use the include file –Contains both the set and multiset classes Constructor multiset > –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.

39 More Methods void insert(arraystart, arrayend) – adds many values to the multiset. The pair class –pair 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 ::iterator, multiset ::iterator> p; p=myset.equal_range(37);

40 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.

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

42 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.

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

44 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

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

46 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)

47 More Algorithms 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. bool equal(start 1, end 1, start 2, func) –Func is an equality boolean function that takes 2 args of type. pair 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. pair<> mismatch(s 1, e 1,s 2, func)

48 Algorithms again 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. remove(s,e,value) –Remove all occurances of value between s and e. remove_copy( s 1,e 1,s 2,value) –s 2 has a copy of s 1 with instances of value removed remove_if( s,e,bool_func) –Removes the value when bool_func is true Remove_copy_if( s 1,e 1,s 2, bool_func)

49 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( s 1,e 1,s 2, old,new) –Makes a copy of the container with instances of old value replaced with new value. replace_copy_if( s 1,e 1,s 2, bool_func,new)

50 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.

51 More math accumulate(s,e,start_value) –Adds up values 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. for_each(s,e,func) –Passes values between s and e to func transform( s 1,e 1,s 2, func) –Passes each value from s to e to func and places the result in container 2.

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

53 Swapping swap(ref, ref) –Takes 2 references and swaps the values iter_swap(iter, iter) –Takes 2 iterators and swaps the values 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

54 More algorithms 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. 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

55 Other Algorithms unique(start, end) –Removes duplicates unique_copy(s 1,e 1,s 2 ) reverse(start,end) –Reverses all the elements reverse_copy(s 1,e 1,s 2 ) 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.

56 Set Operations Values must be ordered in container 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 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. 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.

57 Last of set operations 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. set_union(s 1,e 1,s 2,e 2,r 1 ) –Place the union of containers 1 and 2 into container r.

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

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

60 Last ones min(value 1, value 2 ) max(value 1,value 2 )


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

Similar presentations


Ads by Google