Smart Pointers, deleted functions, and 2-3 trees

Size: px
Start display at page:

Download "Smart Pointers, deleted functions, and 2-3 trees"

Transcription

1 Smart Pointers, deleted functions, and 2-3 trees

2 But first Any questions about your current homework assignment? Due Thursday night by 11:59pm Make-up oral exam: I will have a sign-up sheet on Thursday It will take around minutes I will ask you questions about your code, why you implemented things they way you did, and how some changes would affect the program You will have your program code available, with comments Do not over-comment your code I will remove overly excessive comments

3 heapsort function For sorter.h, you should NOT have a class named sorter Instead, you should have something similar to the following:

4 #ifndef SORTER_H #define SORTER_H #include // stuff template <class T> T* heapsort(t* array, int num) { // code code code } #endif

5 T pop() { assert(size()!= 0);

6 T pop() { if (size() == 0) { throw HeapException( Can t pop when empty ); }

7 T pop() { GZassert(size()!= 0, Can t pop from empty, HeapException);

8

9 Garbage collection Some/many programming languages have a built-in garbage collector that automagically calls delete on data that is no longer being used C# Java Python Go Javascript Ruby Lisp

10 Garbage collection Garbage collection means that objects that are no longer referred to are automatically cleaned up Most of this can be accomplished by reference counting "Dumb" pointers just keep track of what they point to "Smart" pointers keep track of what they point to and how many other things point to what they're pointing to When the count reaches zero, we know we can delete the object and free the memory

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30 1 1 1

31 1 1 1

32 Reference counting usage Reference counting is used in a ton of different places, either alone or as part of a larger garbage collection system Programming languages: C++, Python, Objective-C/Swift, GTK/GObject Unix-style filesystems (Linux, Mac) Reference counting by itself has one weakness:

33

34

35

36

37 Reference counting in C++ C++ comes with the class shared_ptr in the header <memory> You can (but should never) initialize a shared_ptr with an arbitrary pointer Every time you create a shared_ptr from a pointer, you are creating a new reference count for that pointer To avoid this problem, C++ also provides a function named make_shared All of these are templated, so let's look at an example...

38 struct Node { int value; Node *next; }; int stuff() { Node *head = new Node; Node *another = new Node; head->next = another; // stuff } return 0;

39 struct Node { int value; Node *next; }; int stuff() { Node *head = new Node; Node *another = new Node; head->next = another; // stuff } Node *node = head; while (node) { Node *tmp = node; node = node->next; delete tmp; } return 0;

40 struct Node { int value; shared_ptr<node> next; };

41 int stuff() { shared_ptr<node> head = make_shared<node>(); shared_ptr<node> another = make_shared<node>(); head->next = another; // stuff } return 0; int stuff() { Node *head = new Node; Node *another = new Node; head->next = another; // stuff } Node *node = head; while (node) { Node *tmp = node; node = node->next; delete tmp; } return 0;

42 int stuff() { auto head = make_shared<node>(); auto another = make_shared<node>(); head->next = another; // stuff } return 0; int stuff() { Node *head = new Node; Node *another = new Node; head->next = another; // stuff } Node *node = head; while (node) { Node *tmp = node; node = node->next; delete tmp; } return 0;

43 template <class T> struct Node { Node<T>* left; Node<T>* right; T value; }; template <class T> class Tree { private: Node<T> *root; public: //etc... }; bool exists(t val) { Node<T> *node = root; while (node) { if (node->value == val) { return true; } if (val < node->value) { node = node->left; } else { node = node->right; } } return false; }

44 template <class T> struct Node { shared_ptr<node<t>> left; shared_ptr<node<t>> right; T value; }; template <class T> class Tree { private: Node<T> *root; public: //etc... }; bool exists(t val) { Node<T> *node = root; while (node) { if (node->value == val) { return true; } if (val < node->value) { node = node->left; } else { node = node->right; } } return false; }

45 template <class T> struct Node { shared_ptr<node<t>> left; shared_ptr<node<t>> right; T value; }; template <class T> class Tree { private: shared_ptr<node<t>> root; public: //etc... }; bool exists(t val) { Node<T> *node = root; while (node) { if (node->value == val) { return true; } if (val < node->value) { node = node->left; } else { node = node->right; } } return false; }

46 template <class T> struct Node { shared_ptr<node<t>> left; shared_ptr<node<t>> right; T value; }; template <class T> class Tree { private: shared_ptr<node<t>> root; public: //etc... }; bool exists(t val) { auto node = root; while (node) { if (node->value == val) { return true; } if (val < node->value) { node = node->left; } else { node = node->right; } } return false; }

47 public: ~BST() { destructorhelper(root); } private: void destructorhelper(node<t>* node) { if (!node) return; destructorhelper(node->left); destructorhelper(node->right); delete node; }

48

49 class Asdf { public: Asdf(string s) { str = s; } void print() { cout << str << endl; } private: string str; }; int main() { auto asdf = make_shared<asdf>(); }

50

51 In file included from test.cpp:1: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/iostream:38: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/ios:216: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/ locale:15: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/string:439: In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:628: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/memory:2142:49: error: no matching constructor for initialization of 'Asdf' : _T1(_VSTD::forward<_T1_param>( t1)), second_() {} ^ TONS OF LINES REMOVED test.cpp:21:17: note: in instantiation of function template specialization 'std:: 1::make_shared<Asdf>' requested here auto asdf = make_shared<asdf>();

52 In file included from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/memory:83, from test.cpp:2: /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/shared_ptr.h: In constructor std::_sp_counted_ptr_inplace<_tp, _Alloc, _Lp>::_Sp_counted_ptr_inplace(_Alloc) [with _Tp = Asdf, _Alloc = std::allocator<asdf>, gnu_cxx::_lock_policy _Lp = ( gnu_cxx::_lock_policy)2u] : /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/shared_ptr.h:291: instantiated from std:: shared_count<_lp>:: shared_count(std::_sp_make_shared_tag, _Tp*, _Alloc, _Args&&...) [with _Tp = Asdf, _Alloc = std::allocator<asdf>, _Args =, gnu_cxx::_lock_policy _Lp = ( gnu_cxx::_lock_policy)2u] /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/shared_ptr.h:857: instantiated from std:: shared_ptr<_tp, _Lp>:: shared_ptr(std::_sp_make_shared_tag, _Alloc, _Args&&...) [with _Alloc = std::allocator<asdf>, _Args =, _Tp = Asdf, gnu_cxx::_lock_policy _Lp = ( gnu_cxx::_lock_policy)2u] /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/shared_ptr.h:1340: instantiated from std::shared_ptr<_tp>::shared_ptr(std::_sp_make_shared_tag, _Alloc, _Args&&...) [with _Alloc = std::allocator<asdf>, _Args =, _Tp = Asdf] /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/shared_ptr.h:1569: instantiated from std::shared_ptr<_tp1> std::allocate_shared(_alloc, _Args&&...) [with _Tp = Asdf, _Alloc = std::allocator<asdf>, _Args = ] /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/shared_ptr.h:1584: instantiated from std::shared_ptr<_tp1> std::make_shared(_args&&...) [with _Tp = Asdf, _Args = ] test.cpp:22: instantiated from here /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/shared_ptr.h:175: error: no matching function for call to Asdf::Asdf() test.cpp:9: note: candidates are: Asdf::Asdf(std::string) test.cpp:7: note: Asdf::Asdf(const Asdf&)

53 class Asdf { public: Asdf(string s) { str = s; } void print() { cout << str << endl; } private: string str; }; int main() { auto asdf = make_shared<asdf>("test"); }

54 Smart pointers and ada Unfortunately, ada's version of C++ is too old to reliably work in this class When using smart pointers, you can try compiling your code using the following command: g++ -std=c++0x -Wall -g filename.cpp If you were using ada as your main development environment, talk to me and I can help you migrate to something that works better

55 Smart pointers and the rule of three Smart pointers won't save us from the issues requiring the rule of three Smart pointers will prevent us from crashing We would still end up with multiple objects sharing the same memory Sometimes, we don't care about people being able to copy an object

56 template <class T> class BST { public: BST() { } BST(const BST<T>& other) = delete; BST<T>& operator=(const BST<T> &other) = delete; };

57 template <class T> class BST { public: BST() { } BST(const BST<T>& other) = delete; BST<T>& operator=(const BST<T> &other) = delete; }; int main() { BST<int> b; BST<int> c = b; // calls copy constructor }

58 test.cpp: In function int main() : test.cpp:16: error: deleted function BST<T>::BST(const BST<T>&) [with T = int] test.cpp:24: error: used here test.cpp:24:14: error: call to deleted constructor of 'BST<int>' BST<int> c = b; ^ ~ test.cpp:16:5: note: 'BST' has been explicitly marked deleted here BST(const BST<T>& other) = delete; ^ 1 error generated.

59 Going forward in this class You will still need to abide by the rule of three

60 Going forward in this class You will still need to abide by the rule of three Your code should not leak resources, including memory. This means that if a class allocates memory, it MUST have a destructor, and should either delete or implement the assignment operator and copy constructor.

61 Going forward in this class You will still need to abide by the rule of three You should never use new to allocate memory for a single element. Instead, use make_shared<whatevertype>() It's still okay (for now) if you need to allocate an array You should never have a "raw" pointer to a single element, instead you should use shared_ptr<whatevertype>

62 Self-balancing search trees With a simple binary search tree, we can create a situation where we end up with a lopsided tree that looks like a linked list Many search tree operations are O(height) Smarter versions of a search tree can guarantee that the tree is balanced to some degree This can guarantee O(log n) insertion, deletion, and search, regardless of the order of insertion

63 2-3 trees A 2-3 tree is a special type of B-Tree A 2-3 tree contains nodes of two types: 2-nodes are binary search tree nodes 1 data value, 2 children 3-nodes are larger 2 data values, 3 children

64 2-Node V e < V e > V

65 3-Node S L e < S S < e < L e > L

66 template <class T> struct TwoThreeNode { T small; T large; }; shared_ptr<twothreenode<t>> left; shared_ptr<twothreenode<t>> mid; shared_ptr<twothreenode<t>> right;

67 Searching in a 2-3 tree Based on how we search in a binary search tree, how could we search a 2-3 tree to see if an item exists?

68 Searching a 2-3 tree Current node = root While current node is not null: Is this a 2 node? Is the value equal to our value? return true Is the value less than our value? current node = current node->left else current node = current node->right

69 Searching a 2-3 tree // this is a 3 node Is value equal to our smaller value? return true Is value equal to our larger value? return true Is value less than our smaller value? current node = current node->left else, is value less than our larger value? current node = current node->mid else current node = current node->right

70 Adding elements to a 2-3 tree To add elements to a 2-3 tree, let's first talk about what a 4-node is...

71 4-Node S M L e < S S < e < M M < e < L e > L

72 Adding elements to a 2-3 tree We will never create a 4-node directly However, the insertion algorithm is simpler if we think of "temporary" 4-nodes as existing

73 Adding elements to a 2-3 tree Step 1: Find the leaf node where the item to be added should go Step 2: Add the item into the leaf node If leaf node is a 2-node: convert into a 3-node If leaf node is a 3-node: convert to a 4-node, then move the middle element into the parent, carrying the side nodes as children Continue this 4-node removing process until no more 4-nodes exist

74

75 add

76 add

77

78 add

79

80

81

82

83

84 add

85

86 add

87

88

89

90

91

92

93

94

95

96

97 Quiz on Thursday On Thursday, you will have a quiz asking you to perform "add" operations on a number of different 2-3 trees You can generate a series of numbers to add using the following python code (either in a script or interactive): import random random.sample(range(100), 15)

Chapter 20: Binary Trees

Chapter 20: Binary Trees Chapter 20: Binary Trees 20.1 Definition and Application of Binary Trees Definition and Application of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two other

More information

Pointers. Developed By Ms. K.M.Sanghavi

Pointers. Developed By Ms. K.M.Sanghavi Pointers Developed By Ms. K.M.Sanghavi Memory Management : Dynamic Pointers Linked List Example Smart Pointers Auto Pointer Unique Pointer Shared Pointer Weak Pointer Memory Management In order to create

More information

C++ Programming Lecture 7 Software Engineering Group

C++ Programming Lecture 7 Software Engineering Group C++ Programming Lecture 7 Software Engineering Group Philipp D. Schubert Contents 1. Template metaprogramming 2. Variadic template arguments 3. Smart pointer Template metaprogramming Template metaprogramming

More information

Midterm Review. PIC 10B Spring 2018

Midterm Review. PIC 10B Spring 2018 Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed

More information

B-Trees. nodes with many children a type node a class for B-trees. an elaborate example the insertion algorithm removing elements

B-Trees. nodes with many children a type node a class for B-trees. an elaborate example the insertion algorithm removing elements B-Trees 1 B-Trees nodes with many children a type node a class for B-trees 2 manipulating a B-tree an elaborate example the insertion algorithm removing elements MCS 360 Lecture 35 Introduction to Data

More information

G52CPP C++ Programming Lecture 20

G52CPP C++ Programming Lecture 20 G52CPP C++ Programming Lecture 20 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Wrapping up Slicing Problem Smart pointers More C++ things Exams 2 The slicing problem 3 Objects are not

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Heaps. A complete binary tree can be easily stored in an array - place the root in position 1 (for convenience)

Heaps. A complete binary tree can be easily stored in an array - place the root in position 1 (for convenience) Binary heap data structure Heaps A binary heap is a special kind of binary tree - has a restricted structure (must be complete) - has an ordering property (parent value is smaller than child values) Used

More information

Trees, Binary Trees, and Binary Search Trees

Trees, Binary Trees, and Binary Search Trees COMP171 Trees, Binary Trees, and Binary Search Trees 2 Trees Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search,

More information

C:\Temp\Templates. Download This PDF From The Web Site

C:\Temp\Templates. Download This PDF From The Web Site 11 2 2 2 3 3 3 C:\Temp\Templates Download This PDF From The Web Site 4 5 Use This Main Program Copy-Paste Code From The Next Slide? Compile Program 6 Copy/Paste Main # include "Utilities.hpp" # include

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Lecture 15a Persistent Memory & Shared Pointers

Lecture 15a Persistent Memory & Shared Pointers Lecture 15a Persistent Memory & Shared Pointers Dec. 5 th, 2017 Jack Applin, Guest Lecturer 2017-12-04 CS253 Fall 2017 Jack Applin & Bruce Draper 1 Announcements PA9 is due today Recitation : extra help

More information

Binary Search Trees Part Two

Binary Search Trees Part Two Binary Search Trees Part Two Recap from Last Time Binary Search Trees A binary search tree (or BST) is a data structure often used to implement maps and sets. The tree consists of a number of nodes, each

More information

COMP 2355 Introduction to Systems Programming

COMP 2355 Introduction to Systems Programming COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Today Class syntax, Constructors, Destructors Static methods Inheritance, Abstract

More information

Lab 2: ADT Design & Implementation

Lab 2: ADT Design & Implementation Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted

More information

Part I: Short Answer (12 questions, 65 points total)

Part I: Short Answer (12 questions, 65 points total) CSE 143 Sp01 Final Exam Sample Solution page 1 of 14 Part I: Short Answer (12 questions, 65 points total) Answer all of the following questions. READ EACH QUESTION CAREFULLY. Answer each question in the

More information

04-17 Discussion Notes

04-17 Discussion Notes 04-17 Discussion Notes PIC 10B Spring 2018 1 RAII RAII is an acronym for the idiom Resource Acquisition is Initialization. What is meant by resource acquisition is initialization is that a resource should

More information

Lecture 2. Binary Trees & Implementations. Yusuf Pisan

Lecture 2. Binary Trees & Implementations. Yusuf Pisan CSS 343 Data Structures, Algorithms, and Discrete Math II Lecture 2 Binary Trees & Implementations Yusuf Pisan Overview 1. Huffman Coding and Arithmetic Expressions 2. 342 Topics a. Pointers & References

More information

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file? QUIZ on Ch.5 Why is it sometimes not a good idea to place the private part of the interface in a header file? Example projects where we don t want the implementation visible to the client programmer: The

More information

Priority Queues. e.g. jobs sent to a printer, Operating system job scheduler in a multi-user environment. Simulation environments

Priority Queues. e.g. jobs sent to a printer, Operating system job scheduler in a multi-user environment. Simulation environments Heaps 1 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted order. Often we collect a set of items and process the one with the current

More information

Arizona s First University. More ways to show off--controlling your Creation: IP and OO ECE 373

Arizona s First University. More ways to show off--controlling your Creation: IP and OO ECE 373 Arizona s First University. More ways to show off--controlling your Creation: IP and OO ECE 373 Overview Object Creation Control Distribution Possibilities Impact of design decisions on IP control 2 Good

More information

CSCI Trees. Mark Redekopp David Kempe

CSCI Trees. Mark Redekopp David Kempe CSCI 104 2-3 Trees Mark Redekopp David Kempe Trees & Maps/Sets C++ STL "maps" and "sets" use binary search trees internally to store their keys (and values) that can grow or contract as needed This allows

More information

CS 11 C++ track: lecture 1

CS 11 C++ track: lecture 1 CS 11 C++ track: lecture 1 Administrivia Need a CS cluster account http://www.cs.caltech.edu/cgi-bin/ sysadmin/account_request.cgi Need to know UNIX (Linux) www.its.caltech.edu/its/facilities/labsclusters/

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

SCJ2013 Data Structure & Algorithms. Binary Search Tree. Nor Bahiah Hj Ahmad

SCJ2013 Data Structure & Algorithms. Binary Search Tree. Nor Bahiah Hj Ahmad SCJ2013 Data Structure & Algorithms Binary Search Tree Nor Bahiah Hj Ahmad Binary Search Tree A binary search tree has the following properties: For every node n in the tree Value of n is greater than

More information

CA341 - Comparative Programming Languages

CA341 - Comparative Programming Languages CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data

More information

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management Session 8 Memory Management The issues Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Programs manipulate data, which must be stored

More information

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine Homework 5 Yuji Shimojo CMSC 330 Instructor: Prof. Reginald Y. Haseltine July 13, 2013 Question 1 Consider the following Java definition of a mutable string class. class MutableString private char[] chars

More information

Data Abstraction. Hwansoo Han

Data Abstraction. Hwansoo Han Data Abstraction Hwansoo Han Data Abstraction Data abstraction s roots can be found in Simula67 An abstract data type (ADT) is defined In terms of the operations that it supports (i.e., that can be performed

More information

CMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course

CMSC 341 Priority Queues & Heaps. Based on slides from previous iterations of this course CMSC 341 Priority Queues & Heaps Based on slides from previous iterations of this course Today s Topics Priority Queues Abstract Data Type Implementations of Priority Queues: Lists BSTs Heaps Heaps Properties

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 16. Linked Lists Prof. amr Goneid, AUC 1 Linked Lists Prof. amr Goneid, AUC 2 Linked Lists The Linked List Structure Some Linked List

More information

Name: I. 20 II. 20 III. 20 IV. 40. CMSC 341 Section 01 Fall 2016 Data Structures Exam 1. Instructions: 1. This is a closed-book, closed-notes exam.

Name: I. 20 II. 20 III. 20 IV. 40. CMSC 341 Section 01 Fall 2016 Data Structures Exam 1. Instructions: 1. This is a closed-book, closed-notes exam. CMSC 341 Section 01 Fall 2016 Data Structures Exam 1 Name: Score Max I. 20 II. 20 III. 20 IV. 40 Instructions: 1. This is a closed-book, closed-notes exam. 2. You have 75 minutes for the exam. 3. Calculators,

More information

Smart Pointers in C++11

Smart Pointers in C++11 Smart Pointers in C++11 Karl Stratos 1 Background 1.1 Pointers When we write T x to create an instance x of type T, we allocate the amount of memory required for T and names it as x. We can reference (i.e.,

More information

CMSC 341. Binary Search Trees CMSC 341 BST

CMSC 341. Binary Search Trees CMSC 341 BST CMSC 341 Binary Search Trees CMSC 341 BST Announcements Homework #3 dues Thursday (10/5/2017) Exam #1 next Thursday (10/12/2017) CMSC 341 BST A Generic Tree CMSC 341 BST Binary Tree CMSC 341 BST The Binary

More information

Pointers! Arizona State University 1

Pointers! Arizona State University 1 Pointers! CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 10 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section

More information

Module 8: Binary trees

Module 8: Binary trees Module 8: Binary trees Readings: HtDP, Section 14 We will cover the ideas in the text using different examples and different terminology. The readings are still important as an additional source of examples.

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 16 March 17, 2015 1 Introduction In this lecture, we will continue considering ways

More information

Linked List using a Sentinel

Linked List using a Sentinel Linked List using a Sentinel Linked List.h / Linked List.h Using a sentinel for search Created by Enoch Hwang on 2/1/10. Copyright 2010 La Sierra University. All rights reserved. / #include

More information

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A Name: ID#: Section #: Day & Time: Instructor: Answer all questions as indicated. Closed book/closed

More information

CS 201, Fall 2018 Homework Assignment 1

CS 201, Fall 2018 Homework Assignment 1 CS 201, Fall 2018 Homework Assignment 1 Due: 23:59, November 21 (Wednesday), 2018 In this homework, you will implement a music album collection system to store the song names of the music albums in a particular

More information

Lecture 15 Notes Binary Search Trees

Lecture 15 Notes Binary Search Trees Lecture 15 Notes Binary Search Trees 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning, André Platzer, Rob Simmons 1 Introduction In this lecture, we will continue considering ways

More information

Questions: ECE551 PRACTICE Final

Questions: ECE551 PRACTICE Final ECE551 PRACTICE Final This is a full length practice midterm exam. If you want to take it at exam pace, give yourself 175 minutes to take the entire test. Just like the real exam, each question has a point

More information

CS 216 Exam 1 Fall SOLUTION

CS 216 Exam 1 Fall SOLUTION CS 216 Exam 1 Fall 2004 - SOLUTION Name: Lab Section: Email Address: Student ID # This exam is closed note, closed book. You will have an hour and fifty minutes total to complete the exam. You may NOT

More information

CS115 - Module 8 - Binary trees

CS115 - Module 8 - Binary trees Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Section 14. Binary arithmetic expressions Operators such as +,,, and take two arguments, so we call them binary operators.

More information

Final Exam Solutions PIC 10B, Spring 2016

Final Exam Solutions PIC 10B, Spring 2016 Final Exam Solutions PIC 10B, Spring 2016 Problem 1. (10 pts) Consider the Fraction class, whose partial declaration was given by 1 class Fraction { 2 public : 3 Fraction ( int num, int den ); 4... 5 int

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table

More information

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises CS 2308 Spring 2014 Jill Seaman Chapters 1-7 + 11 Write C++ code to: Determine if a number is odd or even Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

21. Dynamic Datatypes and Memory Management

21. Dynamic Datatypes and Memory Management Problem 21. Dynamic Datatypes and Memory Management Last week: dynamic data type Have allocated dynamic memory, but not released it again. In particular: no functions to remove elements from llvec. Today:

More information

CMSC 4023 Chapter 11

CMSC 4023 Chapter 11 11. Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract Data Types Language Examples Parameterized Abstract Data Types Encapsulation Constructs Naming Encapsulations

More information

Module 9: Binary trees

Module 9: Binary trees Module 9: Binary trees Readings: HtDP, Section 14 We will cover the ideas in the text using different examples and different terminology. The readings are still important as an additional source of examples.

More information

Summer Final Exam Review Session August 5, 2009

Summer Final Exam Review Session August 5, 2009 15-111 Summer 2 2009 Final Exam Review Session August 5, 2009 Exam Notes The exam is from 10:30 to 1:30 PM in Wean Hall 5419A. The exam will be primarily conceptual. The major emphasis is on understanding

More information

Function Overloading

Function Overloading Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures

More information

GEA 2017, Week 4. February 21, 2017

GEA 2017, Week 4. February 21, 2017 GEA 2017, Week 4 February 21, 2017 1. Problem 1 After debugging the program through GDB, we can see that an allocated memory buffer has been freed twice. At the time foo(...) gets called in the main function,

More information

C++ Programming Lecture 7 Software Engineering Group

C++ Programming Lecture 7 Software Engineering Group C++ Programming Lecture 7 Software Engineering Group Philipp D. Schubert Contents 1. Template metaprogramming 2. Variadic template arguments 3. Smart pointer Template metaprogramming Template metaprogramming

More information

Lecture 2, September 4

Lecture 2, September 4 Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due

More information

Financial computing with C++

Financial computing with C++ Financial Computing with C++, Lecture 6 - p1/24 Financial computing with C++ LG Gyurkó University of Oxford Michaelmas Term 2015 Financial Computing with C++, Lecture 6 - p2/24 Outline Linked lists Linked

More information

Outline. An Application: A Binary Search Tree. 1 Chapter 7: Trees. favicon. CSI33 Data Structures

Outline. An Application: A Binary Search Tree. 1 Chapter 7: Trees. favicon. CSI33 Data Structures Outline Chapter 7: Trees 1 Chapter 7: Trees Approaching BST Making a decision We discussed the trade-offs between linked and array-based implementations of sequences (back in Section 4.7). Linked lists

More information

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Department of Computer Science Why C? Low-level Direct access to memory WYSIWYG (more or less) Effectively

More information

Dynamic Data Structures (II)

Dynamic Data Structures (II) Lecture 23 Dynamic Data Structures (II) CptS 121 Summer 2016 Armen Abnousi Data Structure Data structures are different ways of organizing data in computer We design new data structures to make the programs

More information

CS 3114 Data Structures and Algorithms DRAFT Project 2: BST Generic

CS 3114 Data Structures and Algorithms DRAFT Project 2: BST Generic Binary Search Tree This assignment involves implementing a standard binary search tree as a Java generic. The primary purpose of the assignment is to ensure that you have experience with some of the issues

More information

Introduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms

Introduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms Introduction to Linked Lists Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms Lecture Slides Friday, September 25, 2009 Glenn G. Chappell Department of Computer Science

More information

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington CSE 333 Lecture 11 - constructor insanity Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia Exercises: - New exercise out today, due Monday morning

More information

Working with Batches of Data

Working with Batches of Data Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html 2 Abstract So far we looked at simple read a string print a string problems. Now we will look at more complex problems

More information

QUIZ Friends class Y;

QUIZ Friends class Y; QUIZ Friends class Y; Is a forward declaration neeed here? QUIZ Friends QUIZ Friends - CONCLUSION Forward (a.k.a. incomplete) declarations are needed only when we declare member functions as friends. They

More information

CSCI-1200 Data Structures Fall 2017 Lecture 17 Trees, Part I

CSCI-1200 Data Structures Fall 2017 Lecture 17 Trees, Part I Review from Lecture 16 CSCI-1200 Data Structures Fall 2017 Lecture 17 Trees, Part I Maps containing more complicated values. Example: index mapping words to the text line numbers on which they appear.

More information

C++ Programming Lecture 4 Software Engineering Group

C++ Programming Lecture 4 Software Engineering Group C++ Programming Lecture 4 Software Engineering Group Philipp D. Schubert VKrit Date: 24.11.2017 Time: 15:45 h Your opinion is important! Please use the free text comments Contents 1. Operator overloading

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section

More information

Outline. A C++ Linked Structure Class A C++ Linked List C++ Linked Dynamic Memory Errors In-class work. 1 Chapter 11: C++ Linked Structures

Outline. A C++ Linked Structure Class A C++ Linked List C++ Linked Dynamic Memory Errors In-class work. 1 Chapter 11: C++ Linked Structures Outline 1 Chapter 11: C++ Linked Structures A ListNode Class To support a Linked List container class LList, a ListNode class is used for the individual nodes. A ListNode object has two attributes: item

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG 1 Notice Class Website http://www.cs.umb.edu/~jane/cs114/ Reading Assignment Chapter 1: Introduction to Java Programming

More information

Come and join us at WebLyceum

Come and join us at WebLyceum Come and join us at WebLyceum For Past Papers, Quiz, Assignments, GDBs, Video Lectures etc Go to http://www.weblyceum.com and click Register In Case of any Problem Contact Administrators Rana Muhammad

More information

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

C++ is Evolving. std::array

C++ is Evolving. std::array C++ is Evolving C++ is an evolving language. A committee of the ISO (International Organization for Standards) ratifies proposed changes to C++. New standards have been released every few years. In this

More information

Class and Function Templates

Class and Function Templates Class and Function 1 Motivation for One Way to Look at... Example: Queue of some type Foo C++ What can a parameter be used for? Instantiating a Template Usage of Compiler view of templates... Implementing

More information

Multiple choice questions. Answer on Scantron Form. 4 points each (100 points) Which is NOT a reasonable conclusion to this sentence:

Multiple choice questions. Answer on Scantron Form. 4 points each (100 points) Which is NOT a reasonable conclusion to this sentence: Multiple choice questions Answer on Scantron Form 4 points each (100 points) 1. Which is NOT a reasonable conclusion to this sentence: Multiple constructors for a class... A. are distinguished by the number

More information

There are, of course, many other possible solutions and, if done correctly, those received full credit.

There are, of course, many other possible solutions and, if done correctly, those received full credit. Question 1. (20 points) STL. Complete the function ChangeWords below. This function has as inputs a vector of strings, and a map of key-value pairs. The function should return a new vector

More information

Motivation for Templates. Class and Function Templates. One Way to Look at Templates...

Motivation for Templates. Class and Function Templates. One Way to Look at Templates... Class and Function 1 Motivation for 2 Motivation for One Way to Look at... Example: Queue of some type Foo C++ What can a parameter be used for? Instantiating a Template Usage of Compiler view of templates...

More information

Programming Abstractions

Programming Abstractions Programming Abstractions C S 1 0 6 B Cynthia Lee Topics du Jour: Make your own classes! (cont.) Last time we did a BankAccount class (pretty basic) This time we will do something more like the classes

More information

21. Dynamic Datatypes and Memory Management

21. Dynamic Datatypes and Memory Management 21. Dynamic Datatypes and Memory Management 695 Problem 696 Last week: dynamic data type Have allocated dynamic memory, but not released it again. In particular: no functions to remove elements from llvec.

More information

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011 More C++ David Chisnall March 17, 2011 Exceptions A more fashionable goto Provides a second way of sending an error condition up the stack until it can be handled Lets intervening stack frames ignore errors

More information

CSE 333 Midterm Exam July 24, Name UW ID#

CSE 333 Midterm Exam July 24, Name UW ID# Name UW ID# There are 6 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes,

More information

examines every node of a list until a matching node is found, or until all nodes have been examined and no match is found.

examines every node of a list until a matching node is found, or until all nodes have been examined and no match is found. A examines every node of a list until a matching node is found, or until all nodes have been examined and no match is found. For very long lists that are frequently searched, this can take a large amount

More information

CMSC 341 Lecture 10 Binary Search Trees

CMSC 341 Lecture 10 Binary Search Trees CMSC 341 Lecture 10 Binary Search Trees John Park Based on slides from previous iterations of this course Review: Tree Traversals 2 Traversal Preorder, Inorder, Postorder H X M A K B E N Y L G W UMBC CMSC

More information

Final Exam. Name: Student ID: Section: Signature:

Final Exam. Name: Student ID: Section: Signature: Final Exam PIC 10B, Spring 2016 Name: Student ID: Section: Discussion 3A (2:00 2:50 with Kelly) Discussion 3B (3:00 3:50 with Andre) I attest that the work presented in this exam is my own. I have not

More information

CSCI 104 Binary Trees / Priority Queues / Heaps. Mark Redekopp Michael Crowley

CSCI 104 Binary Trees / Priority Queues / Heaps. Mark Redekopp Michael Crowley CSCI 04 Binary Trees / Priority Queues / Heaps Mark Redekopp Michael Crowley Trees Definition: A connected, acyclic (no cycles) graph with: A root node, r, that has 0 or more subtrees Exactly one path

More information

CSCI-1200 Data Structures Spring 2018 Lecture 16 Trees, Part I

CSCI-1200 Data Structures Spring 2018 Lecture 16 Trees, Part I CSCI-1200 Data Structures Spring 2018 Lecture 16 Trees, Part I Review from Lecture 15 Maps containing more complicated values. Example: index mapping words to the text line numbers on which they appear.

More information

2 2

2 2 1 2 2 3 3 C:\Temp\Templates 4 5 Use This Main Program 6 # include "Utilities.hpp" # include "Student.hpp" Copy/Paste Main void MySwap (int Value1, int Value2); int main(int argc, char * argv[]) { int A

More information

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am CMSC 202 Section 010x Spring 2007 Computer Science II Final Exam Name: Username: Score Max Section: (check one) 0101 - Justin Martineau, Tuesday 11:30am 0102 - Sandeep Balijepalli, Thursday 11:30am 0103

More information

Assumptions. History

Assumptions. History Assumptions A Brief Introduction to Java for C++ Programmers: Part 1 ENGI 5895: Software Design Faculty of Engineering & Applied Science Memorial University of Newfoundland You already know C++ You understand

More information

Reliable C++ development - session 1: From C to C++ (and some C++ features)

Reliable C++ development - session 1: From C to C++ (and some C++ features) Reliable C++ development - session 1: From C to C++ (and some C++ features) Thibault CHOLEZ - thibault.cholez@loria.fr TELECOM Nancy - Université de Lorraine LORIA - INRIA Nancy Grand-Est From Nicolas

More information

Trees can be used to store entire records from a database, serving as an in-memory representation of the collection of records in a file.

Trees can be used to store entire records from a database, serving as an in-memory representation of the collection of records in a file. Large Trees 1 Trees can be used to store entire records from a database, serving as an in-memory representation of the collection of records in a file. Trees can also be used to store indices of the collection

More information

CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers

CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers Review from Lecture 23 Basic exception mechanisms: try/throw/catch Functions & exceptions, constructors & exceptions Today

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout

More information

Structuur van Computerprogramma s 2

Structuur van Computerprogramma s 2 Structuur van Computerprogramma s 2 dr. Dirk Deridder Dirk.Deridder@vub.ac.be http://soft.vub.ac.be/ Vrije Universiteit Brussel - Faculty of Science and Bio-Engineering Sciences - Computer Science Department

More information

CSE 333 Lecture smart pointers

CSE 333 Lecture smart pointers CSE 333 Lecture 14 -- smart pointers Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia New exercise out today, due Wednesday morning Exam Friday

More information

CSCI-1200 Data Structures Spring 2015 Lecture 18 Trees, Part I

CSCI-1200 Data Structures Spring 2015 Lecture 18 Trees, Part I CSCI-1200 Data Structures Spring 2015 Lecture 18 Trees, Part I Review from Lectures 17 Maps containing more complicated values. Example: index mapping words to the text line numbers on which they appear.

More information

A brief introduction to C++

A brief introduction to C++ A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne

More information

This examination has 11 pages. Check that you have a complete paper.

This examination has 11 pages. Check that you have a complete paper. MARKING KEY The University of British Columbia MARKING KEY Computer Science 252 2nd Midterm Exam 6:30 PM, Monday, November 8, 2004 Instructors: K. Booth & N. Hutchinson Time: 90 minutes Total marks: 90

More information

An Introduction to C++

An Introduction to C++ An Introduction to C++ Introduction to C++ C++ classes C++ class details To create a complex type in C In the.h file Define structs to store data Declare function prototypes The.h file serves as the interface

More information