1 / 19

159.234 LECTURE 17

159.234 LECTURE 17. 23. More on the Standard Template Library. A guided tour with common examples of the containers. More on STL. STL has: bitset a set of bits deque a double ended-queue list a linear list map key value pairs (unique association)

Download Presentation

159.234 LECTURE 17

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. 159.234LECTURE 17 23 More on the Standard Template Library A guided tour with common examples of the containers

  2. More on STL STL has: • bitset a set of bits • deque a double ended-queue • list a linear list • map key value pairs (unique association) • multimap key-value pairs (multiple associations) • multiset set (elements need not be unique) • priority_queue a priority based queue • queue a queue • set a set in which elements are unique • stack a stack • vector a dynamic array

  3. vector<int> v; #include <iostream> #include <vector> using namespace std; int main(){ vector<int> v; vector<int>::iterator it, start, end; for(int i=0;i<10;i++){ v.push_back(i); } cout << "v size = " << v.size() << endl; start = v.begin(); start += 3; // now points at element [3] end = start; end += 4; // now points at element [7] v.erase(start, end ); // erases 3,4,5,6 cout << "v size = " << v.size() << endl; for(it=v.begin();it < v.end();it++){ *it *= 10; } cout << "v contains: "; for(int i=0;i<v.size(); i++){ cout << " " << v[i]; } cout << endl; } Output: % a.out v size = 10 v size = 6 v contains: 0 10 20 70 80 90 A variable-sized vector the range includes all the elements between start and end, including the element pointed by start but not the one pointed by end.

  4. list<int> l1, l2; l1.push_front(2);l1.push_front(4);l1.push_front(6);l1.push_front(8); l2.push_back(1);l2.push_back(3);l2.push_back(5); l2.push_back(7); for(list<int>::iterator it = l1.begin(); it != l1.end(); it++){ cout << *it << " "; } cout << endl; l1.sort(); for(list<int>::iterator it = l1.begin(); it != l1.end(); it++){ cout << *it << " "; } cout << endl; for(list<int>::iterator it = l2.begin(); it != l2.end(); it++){ cout << *it << " "; } cout << endl; l1.merge( l2 ); for(list<int>::iterator it = l1.begin(); it != l1.end(); it++){ cout << *it << " "; } cout << endl; Output: % a.out 8 6 4 2 2 4 6 8 1 3 5 7 1 2 3 4 5 6 7 8 list <T> Doubly-linked list • Allows efficient insertion and deletion at any position in the sequence. • Has all functions of deque, except operator[], and at() functions • Has extra functions: • splice, remove, unique, merge, reverse, sort Merges l2 into the l1 list, inserting all the elements of l2 into l1 at their respective ordered positions. This empties l2 and increases the l1 list size.

  5. map<string,int> m1, m2; map<string,int>::iterator iter; // points to a pair<string,int> string one("One"); string two("Two"); string three("Three"); string four("Four"); string five("Five"); m1[one] = 1; m2[two] = 2; m1[three] = 3; m2[four] = 4; m1[five] = 5; for(iter=m1.begin();iter!=m1.end();iter++){ cout << "Found " << iter->second << " keyed by " << iter->first << endl; } cout << endl; m1.swap(m2); for(iter=m1.begin();iter!=m1.end();iter++){ cout << "Found " << iter->second << " keyed by " << iter->first << endl; } Note: map’s iterator is a pointer to a pair - dereferenced using members first and second Output: % a.out Found 5 keyed by Five Found 1 keyed by One Found 3 keyed by Three Found 4 keyed by Four Found 2 keyed by Two map<key, val> An associative array (or dictionary, or table) • acts like an array whose index can be any type that implements the < operator. • e.g. key=StudentID, • val = Student’s data Record

  6. multimap<string,int> m1; multimap<string,int>::iterator iter; // points to a pair<string,int> string one("One"); string two("Two"); string three("Three"); string four("Four");string five("Five");string six("Six"); m1.insert( m1.end(), make_pair(one, 1) ); // cannot use [] notation m1.insert( m1.end(), make_pair(two, 2) ); m1.insert( m1.end(), make_pair(three, 3) ); m1.insert( m1.end(), make_pair(four, 4) ); m1.insert( m1.end(), make_pair(five, 5) ); m1.insert( m1.begin(), make_pair(six, 6) ); m1.insert( m1.begin(), make_pair(four, 40) ); for(iter=m1.begin();iter!=m1.end();iter++){ cout << "Found " << iter->second << " keyed by " << iter->first << endl; } cout << endl; NB #include<map> , not <multimap>! Output: % a.out Found 5 keyed by Five Found 4 keyed by Four Found 40 keyed by Four Found 1 keyed by One Found 6 keyed by Six Found 3 keyed by Three Found 2 keyed by Two multimap<key, val> Map in which a key can occur many times

  7. stack<T> #include <iostream> #include <stack> using namespace std; int main(){ stack<int> s; // has no iterator cout << "Pushing onto stack: "; for(int i=0; i < 6 ;i++){ cout << " " << i; s.push(i); } for(int i=12; i >= 6 ;i--){ cout << " " << i; s.push(i); } cout << endl; cout << "Stack size " << s.size() << endl; cout << " Top of stack is:"; while( !s.empty() ){ cout << " " << s.top(); s.pop(); // discards top of stack } cout << endl; cout << "Stack size " << s.size() << endl; } Output: % a.out Pushing onto stack: 0 1 2 3 4 5 12 11 10 9 8 7 6 Stack size 13 Top of stack is: 6 7 8 9 10 11 12 5 4 3 2 1 0 Stack size 0 A stack • Allows insertions and deletions only at one end, called its top • adapted from the deque class template • No Iterator

  8. queue<int> q; #include <iostream> #include <queue> using namespace std; int main(){ queue<int> q; // has no iterator for(int i=0; i < 6 ;i++){ q.push(i); } cout << "Queue size " << q.size() << endl; cout << "Queue empty ? " << boolalpha << q.empty() << endl; cout << "Queue contains:"; while( !q.empty() ){ cout << " " << q.front(); q.pop(); // discards head of queue } cout << endl; cout << "Queue size " << q.size() << endl; } Output: % a.out Queue size 6 Queue empty ? false Queue contains: 0 1 2 3 4 5 Queue size 0 A queue, has no iterator, allows duplicate elements • Allows insertions only at one end, called its back (or rear), and deletions only at the other end • adapted from the deque class template • No iterator

  9. priority_queue<T> #include <iostream> #include <queue> #include <functional> #include <vector> using namespace std; int main(){ // priority_queue<int> q; // has no iterator priority_queue<int, vector<int>, less<int> > q; // by default vector is used as container // by default less is used as comparator for(int i=0; i < 6 ;i++){ q.push(i); } cout << "Queue size " << q.size() << endl; cout << "Queue empty ? " << boolalpha << q.empty() << endl; cout << "Priority element is " << q.top() << endl; cout << "Queue priority elements, in order, are:"; while( !q.empty() ){ cout << " " << q.top(); q.pop(); // discards head of queue } cout << endl; cout << "Queue size " << q.size() << endl; } NB #include <queue> , not priority_queue Output (with less): % a.out Queue size 6 Queue empty ? false Priority element is 5 Queue priority elements, in order, are: 5 4 3 2 1 0 Queue size 0 Output (with greater): % a.out Queue size 6 Queue empty ? false Priority element is 0 Queue priority elements, in order, are: 0 1 2 3 4 5 Queue size 0 A queue sorted by value, allows duplicate elements,hasno iterator the top element of the sequence compares largest, or highest priority highest priority element is maintained at the top (or front)

  10. set <T> set<int> s1, s2, s3; set<int>::iterator it; for(int i=9;i>=0;i--){ if( i%2 ) s1.insert(s1.begin(), i); else s2.insert(s2.end(), i); } cout << "size of s1 is " << s1.size() << endl; cout << "size of s2 is " << s2.size() << endl; cout << "s1 contains"; for(it=s1.begin();it != s1.end(); it++){ cout << " " << *it; } cout << endl; cout << "s2 contains"; for(it=s2.begin();it != s2.end(); it++){ cout << " " << *it; } cout << endl; s3 = s1; s3.insert( s2.begin(), s2.end() ); cout << "s3 contains"; for(it=s3.begin();it != s3.end(); it++){ cout << " " << *it; } cout << endl; if( s3.find(4) != s3.end() ) cout << "s3 contains 4" << endl; else cout << "s3 does not contain 4" << endl; if( s3.find(11) != s3.end() ) cout << "s3 contains 11" << endl; else cout << "s3 does not contain 11" << endl; Output: % a.out size of s1 is 5 size of s2 is 5 s1 contains 1 3 5 7 9 s2 contains 0 2 4 6 8 s3 contains 0 1 2 3 4 5 6 7 8 9 s3 contains 4 s3 does not contain 11 A set • like a map with only the unique keys stored • Internally, the elements in a set are always sorted from lower to higher following a specific strict weak ordering criterion set on container construction. The find() function returns an iterator that designates the earliest element in the controlled sequence whose sort key equals key. If no such element exists, the iterator equals end().

  11. multiset<int> ms; multiset<int>::iterator iter; // points to a pair<string,int> ms.insert( ms.end(), 1); // cannot use [] notation ms.insert( ms.end(), 3); ms.insert( ms.end(), 2); ms.insert( ms.end(), 4); ms.insert( ms.end(), 4); ms.insert( ms.end(), 5); cout << "Multiset contains: "; for(iter=ms.begin();iter!=ms.end();iter++){ cout << " " << *iter; } cout << endl; iter = ms.find(3); cout << "Found " << *iter++ << " followed by " << *iter << endl; iter = ms.find(4); cout << "Found " << *iter++ << " followed by " << *iter << endl; ms.erase(iter); cout << "Multiset now contains: "; for(iter=ms.begin();iter!=ms.end();iter++){ cout << " " << *iter; } cout << endl; NB #include <set> ,not multiset! Output: % a.out Multiset contains: 1 2 3 4 4 5 Found 3 followed by 4 Found 4 followed by 4 Multiset now contains: 1 2 3 4 5 multiset<T> A set in which a value can occur many times

  12. #include <iostream> #include <bitset> using namespace std; int main(){ const int N = 24; bitset<N> bs; bs.reset(); bs.set(1); bs.set(2); bs.set(4); bs.set(8); cout << bs[8] << endl; for(int i = N-1; I >= 0; i--){ cout << bs.test(i); if (! ( i%8 ) ) cout << " "; } cout << endl; bs <<= 2 ; for(int i=N-1;i>=0;i--){ cout << bs.test(i); if (! ( i%8 ) ) cout << " "; } cout << endl;} } Output is: % a.out 1 00000000 00000001 00010110 00000000 00000100 01011000 bitset<T> stores a sequence of N bits. • A bit is setif its value is 1, resetif its value is 0. • To flip a bit is to change its value from 1 to 0 or from 0 to 1. • When converting between an object of class bitset<N> and an object of some integral type, bit position j corresponds to the bit value 1 << j. The integral value corresponding to two or more bits is the sum of their bit values. see Bitset.cpp

  13. #include <iostream> #include <bitset> using namespace std; int main(){ const int N = 24; bitset<N> bs; bs.reset(); bs.set(1); bs.set(2); bs.set(4); bs.set(8); cout << bs[8] << endl; for(int i=N-1;i>=0;i--){ cout << bs.test(i); if (! ( i%8 ) ) cout << " "; } cout << endl; bs <<= 2 ; for(int i=N-1;i>=0;i--){ cout << bs.test(i); if (! ( i%8 ) ) cout << " "; } cout << endl;} } Output is: % a.out 1 00000000 00000001 00010110 00000000 00000100 01011000 bitset<T> stores a sequence of N bits. • bitset<N>& reset(); • resets all bits in the bit sequence, then returns *this. • bitset<N>& set(size_t pos, bool val = true); • if pos >= size(), throws out_of_range. • Otherwise, it stores val in the bit at position pos, then returns *this. • bool test(size_t pos, bool val = true); • if pos >= size(), throws out_of_range. • Otherwise, it returns true only if the bit at position pos is set.

  14. // enumeration type for the bits; each bit represents a color enum Color { red, yellow, green, blue, white, black, numColors }; bitset<numColors> usedColors; // create bitset for all bits/colors // set bits for two colors usedColors.set(red); usedColors.set(blue); bitset<T> Another example: • bitset<N> operator<<(const bitset<N>& pos); • member operator function returns bitset(*this) <<= pos. • size_t count() const; • member function returns the number of bits set in the bit sequence. • bitset<N> operator~(); • member operator function returns bitset(*this).flip(). See also Bitset - Colour.cpp See also Bitset - integral to binary.cpp

  15. deque<int> dq; dq.push_back( 4 ); dq.push_back( 5 ); dq.push_front( 3 ); dq.push_front( 2 ); dq.push_front( 1 ); cout << "Max size of deque is " << dq.max_size() << endl; cout << "Element 2 is " << dq[2] << endl; for(deque<int>::iterator it=dq.begin();it!=dq.end();it++){ cout << *it << " "; } cout << endl; deque<int>::iterator it=dq.begin(); it += 3; dq.erase( it ); for(deque<int>::reverse_iterator rit=dq.rbegin();rit!=dq.rend();rit++){ cout << *rit << " "; } cout << endl; deque<int> dq2; dq2.push_front( 30 ); dq2.push_front( 20 ); dq2.push_front( 10 ); dq.swap( dq2 ); for(deque<int>::iterator it=dq.begin();it!=dq.end();it++){ cout << *it << " "; } cout << endl; Output: % a.out Max size of deque is 4,294,967,295 Element 2 is 3 1 2 3 4 5 5 3 2 1 10 20 30 deque<T> Double-ended queue • Allows efficient insertion and deletionat both its beginning and its end • Has all functions of vector, except capacity() and reserve() functions • Extra functions: push_front(), pop_front()

  16. STL provides useful containers Can be parameterised by a contained class iterators useful Not all have iterators See “The Complete Reference C++” Fourth Edition, Herbert Schildt, McGraw Hill, ISBN0-07-222680-3, Chaper 24 and Chapter 33. STL Container Summary

  17. Assign #3: Enhance your Tank Game or Assign #3: Graphical Menu System Optional, in effect cancel thelowest assignment Provided that you submitted at least 3 assignments

  18. Add another instance of your Tank class; incorporate random facilities that would make that Tank move, jump (at Ledges) and shoot at the Alien at different angles, velocity and speed at random time intervals Requirements: Multiple bullets should be released by each Tank object Tank nozzle should be allowed to point at different angles Continue working on your Tank game Improve class architecture to allow for multiple bullets Add another Tank as support Tank Assign #3: Enhance you Tank Game Optional, in effect cancel the lowest assignment Provided that you submitted at least 3 assignments

  19. Graphical menu system Pull-down menu should appear once a menu item is clicked, and retract whenever necessary Simply report on screen which item has been clicked Requirements: Use STL for the core of your menu system Use simple rectangles for the menu items, with labels on them You should provide a documentation for the structure of the file your menu system is able to accept You should also provide a documentation of your system’s class design, as well as all the functions that you incorporate Additional mark for Graphic enhancements Load menu items from a text file Define your own file structure Mouse-clickable menu items and sub menu items Assign #3: Graphical Menu System Optional, in effect cancel the lowest assignment Provided that you submitted at least 3 assignments

More Related