Download presentation
Presentation is loading. Please wait.
Published byHarjanti Tanuwidjaja Modified over 6 years ago
1
Assignment 3 Biggest deductions No decomposition
No Comments describing behavior of stack methods Stack class needs to be usable in any application requiring stack behavior Needs guards (#ifnotdef ----) Use typedef Needs a peek method
2
Assignment 4?
3
Zybook assignment before class on Thursday Ch.17 - recursion
4
Ways in which elements of a container class can be related to each other
Linear (1 - to - 1) Each element has a predecessor and a successor First element has no predecessor, last element has no successor Hierarchical (1 – to – many) Each element has one predecessor and 0 to multiple successors One element (the root) has no predecessor Graph (many to many) Each element has 0 to many predecessors and 0 to many successors Membership Elements do not have predecessors or successors Elements are related by membership only
5
Two Adts that store a collection of items that have no relationship other than membership
6
Set and map Both are value oriented Both have operations to
Add an element Remove an element Find out if an element is a member of the collection Both can be implemented using the same data structures
7
set interface Empty() - return true if set is empty; else return false
Size() - return the number of elements in the set Find(element) - return true if this element is In the set; else return false Add(element) – if this element is not in the set, add it to the set and return true; else return false Remove(element) – if this element is in the set, remove it and return true; else return false
8
Some examples of a set words that appear in a document
Each word in the document is a member of the set ip addresses that are known to be spammers Ip addresses can be added to and removed from the set Set of prime numbers
9
How is a map different from a set?
a map stores elements that are key-value pairs Key is unique identifier Value is other information about the element
10
Some examples of a map Concordance Turkish to English dictionary
Key – a word Value – number of times the word appears in a document Turkish to English dictionary Key – Turkish word Value – the English word Users of a computer system Key – user id Value – password and other information Collection of bank accounts Key – account number Value – balance and other information
11
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an element with this key return true; else return false Add(key, value) – if there is no element with this key, add it to the map and return true; else return false Remove(key) – if there is an element with this key, remove it from the map and return true; else return false Retrieve(key) – if there is an element with this key, return the value; else return null
12
How does a map differ from a set?
Map elements consist of a key and a value Map has a retrieve method Given a key return the associated value In many applications a value is retrieved in order to modify it Ex: deposit or withdraw from a bank account Ex: let a user change her password
13
Dealing with key-value pair
Use Typedef for itemtype Itemtype consists of a key and a value Need Typedef for keytype Need Typedef for valuetype Could write our own class that encapsulates a key and a value Instead will use a template class from the C++ standard library pair<T1, T2>
14
Pair<T1, T2> A template class defined in <utility>
The class pair has 2 public data members First Second Use first for the key Use second for the value
15
Some pair<t1, t2> operations
Constructor Pair<string, int> mypair(“some string”, 36); Make_pair(v1, v2) Returns a pair made from v1 and v2 Pair<string, int> yourpair = Make_pair(“another string”, 27); What is the value of mypair.second yourPair.first
16
example of using pair<T1, T2>
#include<iostream> #include<utility> using namespace std; typedef string KeyType; typedef string ValueType; typedef pair<KeyType, ValueType> ItemType; int main(){ ItemType list[3]; // an array of key-value pairs list[0] = make_pair("John Smith"," "); list[1] = make_pair("Jane Smith"," "); list[2] = make_pair("Bill Jones"," "); for(int i = 0; i < 3; i++){ cout << list[i].first << " has the phone number: " << list[i].second << endl; } /* John Smith has the phone number: Jane Smith has the phone number: Bill Jones has the phone number: */ example of using pair<T1, T2>
17
Changing an item stored in a container
List method retrieve(i) returns the item at position I Map method retrieve(key) returns the value associated with key Suppose we retrieve an item in order to modify it Retrieve a bankaccount from a map in order make a Deposit or withdrawal Retrieve an itemtopurchase from a list in order to change the quantity
18
What will happen? ShopingCart myCart; // add some items to myCart
// including 3 pencils at position 2 ItemType item = myCart.retrieve(2); item.setQuantity(5); ----- item = myCart.retrieve(2); cout << item.getQuantity() << endl;
19
Why?
20
A solution Have retrieve return by reference
Valuetype& retrieve(key Keytype) Itemtype& retrieve (pos int) Would then need: ShopingCart myCart; // add some items to myCart // including 3 pencils at position 2 ItemType item = myCart.retrieve(2); mycart.retrieve(2).setquantity(5); item.setQuantity(5); ----- item = myCart.retrieve(2); cout << item.getQuantity() << endl;
21
Another solution Both user and implementor of a list need to have access to the same item Both need a pointer to the same block of memory Define itemtype as a pointer to itemtype Typedef itemtopurchase* itemtype Would then need: ShopingCart myCart; // add some items to myCart // ex: mycart.append(new itemtopurchase(-----,-----,-----); // including 3 pencils at position 2 ItemType item = myCart.retrieve(2); item->setQuantity(5); ----- item = myCart.retrieve(2); cout << item->getQuantity() << endl;
22
Is Jane Smith’s phone number changed?
#include<iostream> #include<utility> using namespace std; typedef string KeyType; typedef string ValueType; typedef pair<KeyType, ValueType> ItemType; int main(){ ItemType list[3]; // an array of key-value pairs list[0] = make_pair("John Smith"," "); list[1] = make_pair("Jane Smith"," "); list[2] = make_pair("Bill Jones"," "); ValueType phoneNumber = list[1].second; phoneNumber = “ ”; for(int i = 0; i < 3; i++){ cout << list[i].first << " has the phone number: " << list[i].second << endl; } Is Jane Smith’s phone number changed?
23
Define ValueType as a pointer to string
#include<iostream> #include<utility> using namespace std; typedef string KeyType; typedef string* ValueType; typedef pair<KeyType, ValueType> ItemType; int main(){ ItemType list[3]; // an array of key-value pairs list[0] = make_pair("John Smith", new string(" ")); list[1] = make_pair("Jane Smith", new string(" “)); list[2] = make_pair("Bill Jones", new string(" ")); ValueType phoneNumber = list[1].second; *phoneNumber = “ ”; for(int i = 0; i < 3; i++){ cout << list[i].first << " has the phone number: " << *list[i].second << endl; } Define ValueType as a pointer to string
24
What if there is nothing to retrieve?
Retrieve(key) – if there is an item with this key, return the value; else return null Since value is a pointer to the associated value Application can now change the value as needed Return value of null means there is no item with that key
25
Another issue What happens when a node is returned to the heap?
By remove By the destructor By operator= Delete p; P
26
Whose job is it to return the space allocated for the value?
One option: Do it in the map class Delete p->element.second before deleting p General rule: allocator of memory space should return it Application program created the element (including allocating heap memory space for the value) C++11 provides 3 kinds of “smart” pointers will look at the type shared_ptr
27
Shared_ptr An object stored in the heap can be pointed to by multiple pointers If the pointers are “raw” pointers When this object is not accessible by any pointer it becomes “garbage” If the pointers are of type shared_ptr When this object is not accessible by any shared_ptr it is automatically returned to the heap Made possible by a technique known as reference counting An object knows how many pointers can access it
28
The basic idea – raw pointers
a raw_ptr a dynamically created object a raw_ptr a raw_ptr
29
The basic idea – shared pointers
a shared_ptr a dynamically created object a shared_ptr reference count is 3 a shared_ptr
30
#include<iostream>
#include<vector> #include<string> using namespace std; int main() { vector<string*> v; v.push_back(new string("abc")); v.push_back(new string("def")); v.push_back(new string("ghi")); } /* remote03:~/2017/Trials> valgrind ./a.out ==4804== HEAP SUMMARY: ==4804== in use at exit: 108 bytes in 6 blocks ==4804== total heap usage: 9 allocs, 3 frees, 164 bytes allocated remote03:~/2017/Trials> */
31
#include<iostream>
#include<vector> #include<string> #include<memory> using namespace std; int main() { vector<shared_ptr<string>> v; v.push_back(make_shared<string>("abc")); v.push_back(make_shared<string>("def")); v.push_back(make_shared<string>("ghi")); } /* remote03:~/2017/Trials> valgrind ./a.out ==4879== HEAP SUMMARY: ==4879== in use at exit: 0 bytes in 0 blocks ==4879== total heap usage: 9 allocs, 9 frees, 268 bytes allocated ==4879== All heap blocks were freed -- no leaks are possible remote03:~/2017/Trials> */
32
Possible map data structures?
33
Value oriented list data structure add find remove retrieve
vector (unordered) vector (ordered by key) linked list (unordered) linked list (ordered by key)
34
Some map data structures
data structure add find remove retrieve array (unordered) O(n)* O(n) O(n) O(n) array (ordered by key) O(n) O(log2 n) O(n) O(log2 n) linked list (unordered) O(n)* O(n) O(n) O(n) linked list (ordered by key) O(n) O(n) O(n) O(n) * need to make sure key is unique
35
Can we do better? Self-organizing list Search trees Hash table
Add: put at end of a linked list (if not a duplicate key) – O(n) Find and retrieve: linear search and then move element to the beginning of the linked list – O(n) Remove: linear search and then remove – O(n) Search trees Binary search tree Add, find, retrieve and remove all O(log2 n) in the average case, but O(n) in the worst case Balanced search trees Guarantee O(log2 n) add, find, retrieve and remove AVL tree Red-black tree treap Hash table Add, find, retrieve and remove all O(1) but actual performance depends on hash function and load factor
36
Assignment 5 Define and implement a map
Will be a subclass of the abstract class MapInterface Mapinterface is defined in mapinterface.h Use a value-oriented linked list as the implementation data structure store items sorted by key store items unsorted Self-organizing list
37
M A P I N T E R F C Your map tester Map implementation My map tester
38
Looking ahead Next assignment will have same organization as assignment 5 Will implement the map interface using a binary search tree as the data structure
39
Zybook assignment before class on Tuesday march 20 do Ch
Zybook assignment before class on Tuesday march 20 do Ch.19 – binary search trees
40
binary search tree A binary search tree is a binary tree that has the bst property Each node holds a value Its left child is either empty or holds a smaller value Its right child is either empty or holds a larger value 45 36 56 42 25 52 60 30 50
41
Some binary tree terminology
Parent - predecessor of an item Child - successor of an item A child is either a left child or a right child Path - route from one node to another node There is a unique path from the root to each node Leaf - node with no successors Level - root is at level 0, root’s successors are at level 1, etc. Height - length of the longest path 45 36 56 42 25 52 60 30 50
42
Bsts can be defined recursively
A Bst is either empty or Consists of a root which has A left child which is a bst A right child which is bst
43
recursion A function that calls itself is a recursive function
Especially useful when dealing with algorithms and data structures that can be defined recursively Recursion is an alternative to a loop May be simpler to write May be slower to execute May take more memory space Is a tool that programmers should know how and when to use
44
Outline of a recursive function
returnType recFunc (parameters) { if (answer is known) //the base case return answer else //the recursive case call recFunc to solve a smaller version of the same problem
45
Computing n! Non-recursive definition Non-recursive function
fact(0) = 1 fact(n) = n * (n-1) * (n-2) * …. * (for n > 0) Non-recursive function int fact(int n) { assert(n >= 0); int answer = 1; for(int i = n; i > 0; i--) answer = answer * i; return answer; }
46
Computing n! Recursive definition Recursive function
fact(0) = 1 (base case) fact(n) = n * fact(n-1) for n>0 (recursive case) Recursive function ??????
47
int recFact(int n) { assert(n >= 0); if (n == 0) return 1; else return n * recFact(n – 1); }
48
How recursion works every function call results in an activation record being pushed onto the run-time stack holds values for parameters, local variables, etc. as a recursive function is executing there are multiple activation records for that function on the stack activation records are popped from the stack as each recursive call returns to its caller
49
factorial = recFact(4);
main recfact n factorial n ? Run-time stack 4 3 n 2 1
50
Unwinding the recursion
main recfact n factorial n 24 returns 4 * 6 returns 3 * 2 returns 2 * 1 returns 1 * 1 returns 1 4 3 n 2 1
51
When to use recursion? some languages (Lisp) have no loops
recursion is the only way to cause iteration/repetition there are no problems that can only be solved recursively what to consider in deciding between recursion and a loop which leads to an easier to understand solution? are there multiple recursive calls in the recursive solution? binary search, quicksort is the data structure defined recursively? binary search tree does the recursive solution require recomputing values? finding the nth Fibonacci number how deep is the recursion? recursive solution could result in stack overflow
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.