1 / 101

STL Library - Overview

STL Library - Overview. Standard template library accepted in July 1994 into C++ ANSI Standard STL library provides containers, iterators and algorithms designed to work efficiently work parametrically work orthogonally. vector. queue. map. previous. next. begin. end.

washi
Download Presentation

STL Library - Overview

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. STL Library - Overview • Standard template library accepted in July 1994 into C++ ANSI Standard • STL library provides containers, iterators and algorithms designed to • work efficiently • work parametrically • work orthogonally 5/8/2002 1

  2. vector queue map previous next begin end STL - Standard Template Library • Efficient library for basic data structures • Navigation of containers using iterator classes • Algorithms for their use search functions sort functions 5/8/2002 2

  3. STL Based on Templates • Parametric - instantiated with different types • Components used with each other • Uses templates • Native types • User provided types 5/8/2002 3

  4. vectors maps queues STL - Standard Template Library • Parametric - types instantiated • Library for data structures • Provides tools for navigation over containers using iterator classes • begin, end, previous, next • Provides algorithms for their use • sorting, searching functions 5/8/2002 4

  5. Array Example (1 of 3) • #include <iostream.h> • #include <stdlib.h> • #include <time.h> • #include <algorithm> • //QUICKSORT using an vector class • inline double secs(clock_t c) • { return (double)c/CLOCKS_PER_SEC;} • #define N 1000000 • int v[N]; 5/8/2002 5

  6. Array Example (2 of 3) • main() • { • time_t c; • cout <<"\ntime start = " << secs(clock()); • for (int i =0 ; i < N; ++i) • v[i] = rand(); 5/8/2002 6

  7. Array Example (3 of 3) • //uses a quicksort algorithm • cout <<"\nstl sort start = " << secs(c = clock()); • std::sort(v, v + N); • cout <<"\n stl sort = " << secs( clock()-c); • cout << endl; • } • On my pentium 166 megahertz approx 2.8 secs for 1 million keys • On moondance 10 million keys approx 11 seconds 5/8/2002 7

  8. Comments on Array • namespace std::sort() • Used with ordinary vectors • Speedy - compares to hand coded quick sort • Pointer values v and v + N • v is begin address • v + N is end address (one past) 5/8/2002 8

  9. vector list deque set multiset map multimap Two Varieties of Containers • Sequence - ordered by sequence of elements • Associative - keys for looking up elements • Both varieties share a similar interface 5/8/2002 9

  10. Typical Container Interfaces • Constructors • default constructors, copy constructors • Element access • Element insertion • Element deletion • Destructor • Iterators 5/8/2002 10

  11. Overview of Containers • Common set of properties • Constructors and destructors • Element access, insertion and deletion • Allocate and manage memory • Associated allocator objects 5/8/2002 11

  12. Container Members for CAN CAN() default constructor CAN(c) copy constructor c.begin() beginning location of CAN c c.end() ending location of CAN c c.rbegin() beginning for reverse iterator c.rend()ending for reverse iterator c.size() number of elements in CAN c.max_size() largest possible size c.empty() true if the CAN is empty c.swap(d) swap two CANs 5/8/2002 12

  13. Container Operators • == != < > <= >= 5/8/2002 13

  14. Typical Container Algorithm (1 of 2) • double sum(const deque<double> &lst){ • double s = 0; deque<double>::const_iterator c; for (c=lst.begin(); c != lst.end(); ++c) s += *c ; return s;} 5/8/2002 14

  15. Typical Container Algorithm (2 of 2) • deque (double ended queue) container is traversed using a const_iterator • Iterator c is dereferenced to obtain each stored value in turn • Algorithm will work with all containers and all types that have operator+=() defined 5/8/2002 15

  16. Containers with Iterators (1 of 2) • #include <iostream.h> • #include <deque> • using namespace std; • template<class itr> //common stl use of iterator • double sum(itr b, itr e) • { • double s = 0.0; • for( ; b != e; ++b) • s = s + *b; • return s; • } 5/8/2002 16

  17. Containers with Iterators (2 of 2) • //more general abstraction works on vectors • //arrays indeed any container with iterator • int main() • { • //initialize to 10 2.5's • deque< double > data(10, 2.5); • double d[5] = {1.0, 2.5, 3.3, 8.8, 9}; • cout << sum(data.begin(), data.end()) • << endl; • cout << sum(d, d + 5)<< endl; • cout << endl; • } 5/8/2002 17

  18. Comments on Containers with Iterators • Relies on use of iterator range • Most standard idiom • Works with arrays as well using addresses • Will be like an STL numeric algorithm • Note use of constructor for initialization 5/8/2002 18

  19. set multiset map multimap Associative Containers • Key based accessible elements • Ordering relation Compare • Comparison object for the associative container 5/8/2002 19

  20. Associative Container Program (1 of 2) • int main(){ map<string, int, less<string> > name_age; • //key, value stored, ordering • name_age["Pohl,Laura"] = 7; name_age["Dolsberry,Betty"] = 39; cout << "Laura is " << name_age["Pohl,Laura"] << " years old." << endl;} 5/8/2002 20

  21. Associative Container Program (2 of 2) • map name_age is an associative array where key is a string type • Compare object is less<string> 5/8/2002 21

  22. Additional Associative Definitions ASSOC::key_type retrieval key type ASSOC::key_compare comparison object type ASSOC::value_compare type for comparing ASSOC::value_type 5/8/2002 22

  23. Associative Insert & Erase Functions (1 of 2) c_unique.insert(t) Insert t, if no existing key t c_eq.insert(w_it, t) Insert t, return position w_it c.insert(w_it, t) Insert t with starting position w_it for search (fails on sets and maps if key value already exists) c(b_it, e_t) Inserts element range c.erase(k) Erases elements with key k,return # erased elements c.erase(w_it) Erases pointed to element c.erase(b_it, e_t) Erases range of elements 5/8/2002 23

  24. Associative Member Functions c.find(k) Returns iterator to element having key k, otherwise end c.count(k) Returns # of elements with k c.lower_bound(k) Returns iterator to first element having value greater than or equal to k c.upper_bound(k) Returns iterator to first element having value greater than k c.equal_range(k) Returns iterator pair for lower_bound & upper_bound 5/8/2002 24

  25. stack queue priority_queue Container Adapter Classes • Modify existing containers to produce different public behaviors based on existing implementation • stack can be adapted from vector, list and deque • Last in first out data structure • Supports back, push_back and pop_back 5/8/2002 25

  26. Adapted Stack Functions void push(const value_type& v)Place v on stack void pop() Remove top element value_type& top() const Return top element bool empty() constReturns true if stack empty size_type size() const Returns # of elements operator== and operator< Equality and less supported 5/8/2002 26

  27. vector list deque Sequence Containers • Sequence containers have a sequence of accessible elements • C++ array type can also be treated as a sequence container 5/8/2002 27

  28. Sequence Container Program (1 of 3) • //inserting a vector into a dequeint main(){ int data[5] = { 6, 8, 7, 6, 5 }; vector<int> v(5, 6); //5 element vect deque<int> d(data, data + 5); deque<int>::iterator dq_it; 5/8/2002 28

  29. Sequence Container Program (2 of 3) • cout << "\n Deque values\n\n"; for (dq_it = d.begin(); dq_it != d.end(); ++dq_it) cout << *dq_it << '\t'; //print:6 8 7 6 5 cout << endl; d.insert(d.begin(), v.begin(), v.end()); for (dq_it = d.begin(); dq_it != d.end(); dq_it++) cout << *dq_it << '\t'; • //print:6 6 6 6 6 6 8 7 6 5} 5/8/2002 29

  30. Sequence Container Program (3 of 3) • 5 element vector v initialized with value 6 • deque d initialized with values taken from array data • insert() member function places v values in specified range v.begin() to v.end() at location d.begin() 5/8/2002 30

  31. Additional Sequence Members in SEQ SEQ::SEQ(n, v)n elements of value v SEQ::SEQ(b_it, e_it) start at b_it and go to e_it - 1 c.insert(w_it, v)insert v before w_it c.insert(w_it, v, n) insert n copies of v before w_it c.insert(w_it, b_it, insert b_it to e_it e_it) before w_it c.erase(w_it) erases element at w_it c.erase(b_it, e_it)erase b_it to e_it 5/8/2002 31

  32. Adapted Containers (1 of 2) • Include Stack, Queue, Priority Queue • Stack adapted from vector, list, or deque • Stack adapted from user defined container with operations empty, size, push_back, pop_back, and back operations • stack < list < double > > stk • Supports stack operations 5/8/2002 32

  33. Adapted Containers (2 of 2) • Queue adapted from list or deque but not vector • needs push_back, pop_front • Priority queue can be adapted from vector or deque • need random access 5/8/2002 33

  34. Stack Adapted from Vector (1 of 2) • int main(){ stack<vector<string> > str_stack; • string quote[3] = {"The wheel that squeaks the loudest\n", "Is the one that gets the grease\n", "Josh Billings\n" }; 5/8/2002 34

  35. Stack Adapted from Vector (2 of 2) • for (int i =0; i < 3; ++i) str_stack.push(quote[i]); while (!str_stack.empty()) { cout << str_stack.top(); str_stack.pop(); }} 5/8/2002 35

  36. forward • input • output Iterators • Means for navigating data structure • Iterators in STL are pointer-style objects used to return with data stored in containers • Iterators in STL come in 5 categories random access bidirectional 5/8/2002 36

  37. Iterators and Containers and Algorithms • Algorithm may not support all iterator categories • List will not support random access iterator but will support bidirectional iterators • Sorting requires random access but finding requires only input iterator • Vector containers allow random access 5/8/2002 37

  38. Input Iterator • Equality, dereferencing, autoincrement • One pass algorithms read values in one direction • Conforms to following properties where Iter has first and first != lastfirst++//accesses next element • *first defined and can be used to compare, increment, dereference and assign elements of type Iter • Special case istream_iterator 5/8/2002 38

  39. istream_iterator for Reading from Streams • int main(){ int d[5]; • cout << "\nEnter integers: "; istream_iterator<int,ptrdiff_t> in(cin); for (int i = 0; i < 5; ++i) { d[i] = *in++; cout << "\nd[" << i << "] = " << d[i] << endl; }} 5/8/2002 39

  40. Output Iterator • Supports dereferencing restricted to left hand side of assignment and autoincrement • One pass algorithms write values in one direction • If Iter is output iterator type withIter ptr • *ptr can be on the left hand side of assignment • ptr++ is defined 5/8/2002 40

  41. The output is all run together! Special case ostream_iterator Use the char* \t delimiter and a tab character will be issued to cout after each int value written 5/8/2002 41

  42. The ostream_iterator for Writing to Streams • int main(){ int d[5] = {2, 3, 5, 7, 11}; //primes ostream_iterator<int> out(cout, "\t"); for (int i = 0; i < 5; ++i) *out = d[i] ;} 5/8/2002 42

  43. Forward Iterator • Supports all input/ output operations • Supports unrestricted use of assignment • Allows position within data structure retained from pass to pass • One directional multi-pass algorithms • Able to save position and restart an algorithm from that position 5/8/2002 43

  44. Bidirectional Iterator • Supports all forward iterator operations • Supports both autoincrement and autodecrement • General bidirectional multi-pass algorithms 5/8/2002 44

  45. Random Access Iterators Any location is accessible in constant time 5/8/2002 45

  46. Random Access Iterators Support • All bidirectional operations • General bidirectional multi-pass algorithms • Address arithmetic operations & comparison • ptr += n and ptr -= n • ptr1 - ptr2 5/8/2002 46

  47. STL Algorithms Library • Sorting algorithms • Non-mutating sequence algorithms • Mutating sequence algorithms • Numerical algorithms • Generally use iterators to access containers instantiated on given type • Resulting code can be competitive in efficiency with special purpose codes 5/8/2002 47

  48. Sorting Algorithms • General sorting, merge, heap, permutation, lexicographic comparison, binary search and selected other like operations • Algorithms have versions that use either operator<() or Compare object 5/8/2002 48

  49. Using sort() for In-Memory quicksort • const int N = 5;int main(){ int d[N], i, *e = d + N; for (i = 0; i < N; ++i) d[i] = rand(); sort(d, e); for (i = 0; i < N; ++i) cout << d[i] << '\t';} 5/8/2002 49

  50. Sorting Algorithm Prototypes (1 of 6) • template<class RandAcc>void sort(RandAcc b, RandAcc e); • Quicksort algorithm over elements b to e • template<class RandAcc>void stable_sort(RandAcc b, RandAcc e); • Stable sorting algorithm over elements b to e • Elements remain in their relative same position 5/8/2002 50

More Related