Sets and MultiSets. Contents. Steven J. Zeil. July 19, Overview of Sets and Maps 4
|
|
- Daniel Randall
- 6 years ago
- Views:
Transcription
1 Steven J. Zeil July 19, 2013 Contents 1 Overview of Sets and Maps 4 1
2 2 The Set ADT The template header Internal type names Constructors & Assignment Status Insert & Erase Access Searching for Ranges of Equal Items A Simple Example of Using Set 34 CS361 2
3 The data structures and ADTs we have looked at so far in this course have been what are sometimes called sequential containers - they maintain elements in a known sequence and we access the elements by indicating a position in the sequence from which we wish to obtain an element. Sometimes we indicate this position numerically (e.g., a[23]), sometimes symbolically (e.g., myvector.front()), but always, in order to get an element, we have to know where it is in relation to the other elements. Now we turn our attention to associative containers, ones in which the container s implementation maintains the elements in a sequence that is intended to allow rapid access to elements based upon their value. This section of the course will be a bit different from the ones that have gone before. Previously, we have introduced an abstraction (vector, list, deque, etc) and also discussed how to implement it. The implementation of sets and maps is difficult enough, however, that we ll want to look at different possible underlying data structures, so for right now we ll only look at the set and map ADTs and how to use them, and we ll leave the imple- CS361 3
4 mentation for later. 1 Overview of Sets and Maps The major associative classes in the standard library are set map multiset multimap Sets are containers to which we can add elements (called keys ) and later check to see if certain key values are present in the set. CS361 4
5 Maps, also known in other contexts as lookup tables or dictionaries, allow us to store pairs consisting of a key value and associated data value 1 and to later look up the data value, if any, associated with a given key. In a set or a map, a given key value may appear only once. Attempting to add a key K to a set replaces any existing key equal to K. Adding a key-data pair (K,D1) to a map that already has (K,D2) replaces (K,D2) by (K,D1). But in a multiset or multimap, the same key can occur any number of times. For a multiset, this means that instead of just asking is K in this set? we can now ask how many K s are in this set?. For a multimap, adding a key-data pair (K,D1) to a multimap that already has (K,D2) results in multimap that has both (K,D1) and (K,D2). 1 In some contexts, especially more mathematical ones, the set of keys is called the domain of the map and the set of associated data values is called the range of the map. CS361 5
6 We ll look at sets and multisets first, and then turn to maps and multimaps in a later lecture. 2 The Set ADT A set collects elements and lets you check to see if an element is already in the collection. A given element can occur at most once in a set. Provides iterators that allow you to list the elements in sorted order. # ifndef SET_H #define SET_H #include <cstddef > CS361 6
7 template <class Key, class Compare=less <Key> > class set { private : Compare comparator ; public : / / typedefs : typedef Key key_type ; typedef Key value_type ; typedef Compare key_compare ; typedef Compare value_compare ; CS361 7
8 typedef const Key& reference ; typedef const Key& const_reference ; typedef... c o nst_iterator ; typedef c o nst_iterator i t e r a t o r ; typedef... const_reverse_iterator ; typedef const_reverse_iterator r e v e r s e _ i t e r a t o r ; typedef... size_type ; typedef... difference_type ; / / allocation / deallocation explicit set ( const Compare& comp = Compare ( ) ) ; CS361 8
9 set ( const set <Key, Compare>& x ) ; template <class InputIterator > set ( InputIterator f i r s t, InputIterator l a s t, const Compare& comp = Compare ( ) ) ; set <Key, Compare>& operator =( const set <Key, Compare>& x ) ; / / accessors : key_compare key_comp ( ) const { return comparator ; } value_compare value_comp ( ) const { return comparator ; } CS361 9
10 i t e r a t o r begin ( ) const ; i t e r a t o r end ( ) const ; r e v e r s e _ i t e r a t o r rbegin ( ) const { return t. rbegin ( ) ; } r e v e r s e _ i t e r a t o r rend ( ) const { return t. rend ( ) ; } bool empty ( ) const { return ( s i z e ( ) == 0 ) ; } size_type s i z e ( ) const ; size_ type max_size ( ) const ; void swap( set <Key, Compare>& x ) ; / / i n s e r t / erase pair < i t e r a t o r, bool> i n s e r t ( const value_type& x ) ; CS361 10
11 i t e r a t o r i n s e r t ( i t e r a t o r position, const value_type& x ) ; void clear ( ) ; void erase ( i t e r a t o r position ) ; size_ type erase ( const key_type& x ) ; void erase ( i t e r a t o r f i r s t, i t e r a t o r l a s t ) ; / / s e t operations : i t e r a t o r find ( const key_type& x ) const ; size_ type count ( const key_type& x ) const ; CS361 11
12 i t e r a t o r lower_bound ( const key_type& x ) const ; i t e r a t o r upper_bound ( const key_type& x ) const ; pair < i t e r a t o r, i t e r a t o r > equal_range ( const key_type& x ) const ; private :. / / declaration of implementing data structure } ; template <class Key, class Compare> bool operator ==( const set <Key, Compare>& x, const set <Key, Compare>& y ) ; CS361 12
13 template <class Key, class Compare> bool operator< ( const set <Key, Compare>& x, const set <Key, Compare>& y ) ; #endif The interface to multiset is identical to that of the set (aside from replacing the name set by multiset ) - it s only the behavior of a few of the operations that differ. So, as we look at the set interface, keep in mind that the same things apply to multisets as well. CS361 13
14 2.1 The template header Typically, you would declare a set by instantiating the template on the date type that template <class Key, class Compare=less <Key> > you want to use for the key: class set { set <string > mystringset ; But as you can see from the template header, this is an oversimplification. There is a second parameter, Compare, that supplies the comparison function to be used in comparing elements of the set. This parameter is given a default value, less<key>, so the above instantiation is actually equivalent to set <string, less <string > > mystringset ; What does less<...> do? It simply uses the Key s own operator< to do the compar- CS361 14
15 isons, and that s good enough 90% of the time. 2 Actually, even this template header is somewhat oversimplified. The real header has yet another parameter: template <class Key, class Compare=less <Key>, class Allocator = allocator <Key> > class set { but the Allocator parameter is only used in very rare situations where the application needs specialized control over how memory for the set will be allocated. We won t worry about that in this course. 2 less is a rather odd creature, however. It s actually a template for a class of functors (48), which we first encountered some time ago. CS361 15
16 2.2 Internal type names / / typedefs : Many standard containers provide a set of typedef Key key_type ; type names for programming convenience typedef Key value_type ; and to provide a standard way of declaring things without making direct reference typedef Compare key_compare ; typedef Compare value_compare ; to the data structures used to implement typedef const Key& reference ; them. We ve seen this with type names like typedef const Key& const_reference vector::const_iterator ; and list::size_type and typedef... const_iterator ; typedef c o nst_iterator i t e r a t o r ; we have used the same technique in our own programming (e.g., CS361Set::iterator). The associative containers add a couple of useful type names. The name key_type CS361 16
17 gives the data type of the keys in the container. The name value_type gives the data type that describes what we insert into the container and what is returned whenever we dereference (apply operator* to) an iterator. For set and multiset, the value_type is the same as the key_type, but that won t be true when we get to map and multimap. 2.3 Constructors & Assignment e x p licit set ( const Compare& comp = Compare ( ) ) ; set ( const set <Key, Compare>& x ) ; template <class InputIterator > set ( InputIterator f i r s t, InputIterator l a s t, const Compare& comp = Compare ( ) ) ; CS361 17
18 set <Key, Compare>& operator =( const set <Key, Compare>& x ) ; Looking at the constructors for set, the most interesting things are The first constructor takes a single parameter, a comparator. But we already supply a comparator when we instantiate the class! It turns out that when we instantiate the class, e.g., typedef set <string, less <string > > MySetType ; we re only telling the compiler what the default comparator should be. We can use that default: MySetType ascendingorder ; / / uses < to compare s t r i n g s or we can create objects that use a different comparator: MySetType descendingorder ( greater <string > ( ) ) ; / / uses > to compare s t r i n g s CS361 18
19 Note that, because this constructor has a default value for its only parameter, we can use it, as we did above, as the default constructor for the class. (If you don t remember what a default constructor is, go back to the ADTs lectures.) The third constructor lets us build a new set from any range specified by a pair of iterators. For example, vector <string > v ;. multiset <string > ms ( v. begin ( ), v. end ( ) ) ; CS361 19
20 2.4 Status bool empty ( ) const { return ( s i z e ( ) == 0 ) ; } No surprises here... size_type s i z e ( ) const ; size_ type max_size ( ) const ; CS361 20
21 2.5 Insert & Erase / / i n s e r t / erase pair < i t e r a t o r, bool> i n s e r t ( const value_type& x ) ; i t e r a t o r i n s e r t ( i t e r a t o r position, const value_type& x ) ; As described in your text, void clear ( ) ; s. i n s e r t ( " def " ) ; void erase ( i t e r a t o r position ) ; adds a new element, "def", into s. size_ type erase ( const key_type& x ) ; void erase ( i t e r a t o r f i r s t, i t e r a t o r l a s t ) ; CS361 21
22 If something equal to "def" is already in the set, nothing happens. But in a multiset, we would go ahead and add a second copy of "def". The return type from this operation is a bit interesting. There s two things you might want to know after trying to add something to a set: 1. Did it go in? (i.e., was this key already in the set), or 2. Where is it in the set? Rather than choose between these two equally valuable pieces of information, the insert operation actually returns both of them in a pair. (The std::pair template was one of our first examples of a class template (77).) It returns a pair (b,p) where b is a bool indicating whether an insertion occurred, and p is the position where the key was inserted. You are supposed to ignore the value of p if b is false. CS361 22
23 The second of the two insert functions is a bit odd: s. i n s e r t ( position, " def " ) ; Since this is an associative container, it s supposed to decide where to put things. Why then might we supply a position? The position is taken as a "hint" of where to begin searching for position to insert. The set implementation may ignore the hint if a quick check shows that the new key really does not belong at that position. But the C++ standard says that we are guaranteed that this hint version of insert will have an amortized O(1) worst case if we have data that is already in order and we use the position where one key was inserted as the hint for the next larger key, e.g.: CS361 23
24 vector <int > v ;. sort ( v. begin ( ), v. end ( ), less <int > ( ) ) ; / / we know the elements of v are in order set <int > myset ; set <int > : : i t e r a t o r hint = myset. begin ( ) ; for ( int i = 0 ; i < v. s i z e ( ) ; ++ i ) { hint = myset. i n s e r t ( hint, v [ i ] ) ; / / amortized O(1) i n s e r t s ++hint ; } Many generic algorithms expect an insert operation of this form. In particular, suppose we wanted to copy a list into a set. You may remember that we can t do this: CS361 24
25 l i s t <Foo> foolist ;. set <Foo> fooset ; copy ( f o o L i s t. begin ( ), foolist. end ( ), fooset. begin ( ) ) ; Question: Why doesn t this copy work? CS361 25
26 Answer: l i s t <Foo> foolist ;. set <Foo> fooset ; copy ( f o o L i s t. begin ( ), foolist. end ( ), fooset. begin ( ) ) ; The copy does not work here because copy simply writes into its destination positions it doesn t allocate new space for stuff, it assumes that the space already exists When we faced this problem copying into vectors and lists, we got around it by using back_inserter: l i s t <Foo> foolist ;. vector <Foo> foovect ; copy ( f o o L i s t. begin ( ), foolist. end ( ), back_inserter ( foovect ) ) ; CS361 26
27 back_inserter is a function that returns a special iterator that uses push_back whenever we try to store something at the iterator. Now that won t help for copying into sets, because sets don t have a push_back function. But another iterator-returning function is inserter, that returns an iterator that uses insert(position,value) whenever we try to store to it. For example, we can copy into the middle of a vector this way: l i s t <Foo> foolist ; vector <Foo> foovect ;. copy ( f o o L i s t. begin ( ), foolist. end ( ), i n s e r t e r ( foovect, foovect. begin ( ) + foovect. s i z e ( ) / 2 ) ) ; And, to finally get to the point of all this, because set and multiset have a member function that looks like insert(position,value), we can use inserter with them as well: CS361 27
28 l i s t <Foo>. foolist ; set <Foo> fooset ; copy ( f o o L i s t. begin ( ), foolist. end ( ), i n s e r t e r ( fooset, fooset. end ( ) ) ) ; If the list is unsorted, then the position supplied to inserter is only a hint. But if the list were sorted already, then this copy would get the amortized O(1) hint benefit, and the entire copy would be accomplished in O(fooList.size()) time. 2.6 Access i t e r a t o r find ( const key_type& x ) const There ; are two ways to see if an element is size_ type count ( const key_type& x ) const present ; in a set: CS361 28
29 set <string, less <string > > : : i t e r a t o r i ; i = s. find ( "abc" ) ; We can search the set for "abc". If the key is found, find returns the position where that element resides. If not found, it returns s.end(). So it s not unusual to see code that looks like: i f ( myset. find (yourname)! = myset. end ( ) ) cout << " I found " << yourname << " in my set. " << endl ; Alternatively, we can count the number of times we find an element. i f ( myset. count (yourname) > 0) { cout << " I found " << yourname << " in my set. " << endl ; cout << " I found there " << myset. count (yourname) << " times. " << endl ; } CS361 29
30 Of course, for sets, count(...) will always return 0 or 1, because either the key isn t in there at all, or there s only one copy of it in the set. But for multiset, count may return any non-negative number Searching for Ranges of Equal Items Suppose that we re interested, not i t e r a t o r lower_bound ( const key_type& x ) const ; so much in whether or not an element is present, but in where it i t e r a t o r upper_bound ( const key_type& x ) const ; pair < i t e r a t o r, i t e r a t o r > equal_range ( const key_type& might be. x ) const ; We can, as we have seen, use find to get the position of an element in a set. But if we have a multiset, there may be many instances of the same key. How do we know which instance will be pointed out by find? CS361 30
31 The functions shown here allow us to get the positions of all keys equal to some specified value. lower_bound returns the position of the first element in the set/multiset with the indicated value. upper_bound returns the position just after the last element equal to a given value. equal_range returns a pair consisting of both the lower_bound and the upper_bound. For example, a library system, having many copies of the same book, might keep track of its books by ISBN number: class Book { public :. s t r i n g author ( ) const ; s t r i n g t i t l e ( ) const ; s t r i n g isbn ( ) const ; int copynumber ( ) const ; CS361 31
32 bool ischeckedout ( ) const ; } ; bool operator < ( const Book& l e f t, const Book& r i g h t ) { return l e f t. isbn ( ) < r i g h t. isbn ( ) ; } Then, given a multiset of books: typedef multiset <Book, less <Book> > Holdings ; Holdings l i b r a r y ; we could list all the copies of a given book that are checked out this way: const s t r i n g textisbn = " " ; pair <Holdings : : i t e r a t o r, Holdings : : i t e r a t o r > rng CS361 32
33 = l i b r a r y. equal_range ( textisbn ) ; for ( Holdings : : i t e r a t o r i = rng. f i r s t ; i!= rng. second ; ++ i ) { i f ( i >ischeckedout ( ) ) cout << "Copy " << i >copynumber ( ) << " i s checked out. " << endl ; } Both set and multiset support these operations, though they aren t really very useful for sets. By the way, this is a good example of a place where the new C++11 auto type declaration and range-based for loop can simplify the code: const s t r i n g textisbn = " " ; auto rng = l i b r a r y. equal_range ( textisbn ) ; CS361 33
34 for ( auto i : rng ) { i f ( i >ischeckedout ( ) ) cout << "Copy " << i >copynumber ( ) << " i s checked out. " << endl ; } The first auto matches the pair type and the second matches the iterator type. 3 A Simple Example of Using Set As part of a program to be presented in a later example, we need to read an English language document in plain text form and collect all the words that are used to begin sentences. For example, if we read CS361 34
35 Hello! How are you? I haven t seen you in a long time. How is your family? we would want a set with the words Hello!, How, and I. 3 This is a pretty straightforward application for set, and here is the code to collect the sentence-starting words: void readdocument ( const char * docfilename, set <string >& startingwords,... ) { ifstream docin ( docfilename ) ; char lastchar =. ;. 3 Unlike in our spell checker, this particular application will need us to preserve all upper/lower case distinctions and to treat punctuation as part of the preceding word. CS361 35
36 s t r i n g word ; } while ( docin >> word) { i f ( lastchar ==. lastchar ==? lastchar ==! ) { startingwords. i n s e r t (word ) ; } lastchar = word [ word. length ( ) 1];. } CS361 36
Standard Library Reference
Standard Library Reference This reference shows the most useful classes and functions in the standard library. Note that the syntax [start, end) refers to a half-open iterator range from start to end,
More informationProgramming with Haiku
Programming with Haiku Lesson 2 Written by DarkWyrm All material 2010 DarkWyrm In our first lesson, we learned about how to generalize type handling using templates and some of the incredibly flexible
More informationA Standard flat_map. 1 Revisions. 2 Introduction. 3 Motivation and Scope. 1.1 Changes from R Changes from R0
A Standard flat_map Document Number: P0429R2 Date: 2016-08-31 Reply to: Zach Laine whatwasthataddress@gmail.com Audience: LWG/LEWG 1 Revisions 1.1 Changes from R1 Add deduction guides. Change value_type
More informationDocument Number: P0429R4 Date: Reply to: 0.1 Revisions... 1
Document Number: P0429R4 Date: 2018-05-05 Reply to: Zach Laine whatwasthataddress@gmail.com Audience: LWG A Standard flat_map Contents Contents i 0.1 Revisions.............................................
More informationOutline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation
Outline EDAF30 Programming in C++ 4. The standard library. Algorithms and containers. Sven Gestegård Robertz Computer Science, LTH 2018 1 Type inference 2 3 The standard library Algorithms Containers Sequences
More informationLecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides.
Lecture 21 Standard Template Library STL: At a C++ standards meeting in 1994, the committee voted to adopt a proposal by Alex Stepanov of Hewlett-Packard Laboratories to include, as part of the standard
More informationSummary. Design. Layout
Flat containers wording Document number: P0460R0 Date: 2016-10-15 Reply-to: Sean Middleditch sean@middleditch.us Project: ISO JTC1/SC22/WG21: Programming Language C++ Audience: Library Evolution Working
More informationA Standard flat_map. Drop the requirement on container contiguity; sequence container will do.
A Standard flat_map Document umber: P9R Date: 6-8- Reply to: Zach Laine whatwasthataddress@gmail.com Audience: LWG/LEWG Revisions. Changes from R Drop the requirement on container contiguity; sequence
More informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing STL and Iterators Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer Semester
More informationA Standard flat_set. This paper outlines what a (mostly) API-compatible, non-node-based set might look like.
A Standard flat_set Document Number: P1222R0 Date: 2018-10-02 Reply to: Zach Laine whatwasthataddress@gmail.com Audience: LEWG 1 Introduction This paper outlines what a (mostly) API-compatible, non-node-based
More information2
STL Design CSC 330 2 3 4 5 Discussions Associative Containers 6 7 Basic Associative Containers 8 set class 9 map class 10 Example multiset (1) 11 Example multiset (2) 12 Example multiset (3) 13 Example
More informationCSCE 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 informationSTL Containers, Part II
CS106L Handout #08 Fall 2007 October 17, 2007 STL Containers, Part II Introduction Last week we talked about vector and deque, the STL's two managed array classes. However, the STL offers many other containers,
More informationCOEN244: Class & function templates
COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library
More informationCS11 Advanced C++ Spring 2018 Lecture 2
CS11 Advanced C++ Spring 2018 Lecture 2 Lab 2: Completing the Vector Last week, got the basic functionality of our Vector template working It is still missing some critical functionality Iterators are
More informationChapter 5. The Standard Template Library.
Object-oriented programming B, Lecture 11e. 1 Chapter 5. The Standard Template Library. 5.1. Overview of main STL components. The Standard Template Library (STL) has been developed by Alexander Stepanov,
More informationLesson 13 - Vectors Dynamic Data Storage
Lesson 13 - Vectors Dynamic Data Storage Summary In this lesson we introduce the Standard Template Library by demonstrating the use of Vectors to provide dynamic storage of data elements. New Concepts
More informationCSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too)
CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too) HW6 NOTE: Do not use the STL map or STL pair for HW6. (It s okay to use them for the contest.)
More informationPatterns: Working with Arrays
Steven Zeil October 14, 2013 Outline 1 Static & Dynamic Allocation Static Allocation Dynamic Allocation 2 Partially Filled Arrays Adding Elements Searching for Elements Removing Elements 3 Arrays and Templates
More informationA Standard flat_map. 1 Introduction. 2 Motivation and Scope
A Standard flat_map Document umber: P49R Date: 6-8-3 Reply to: Zach Laine whatwasthataddress@gmail.com Audience: LWG/LEWG Introduction This paper outlines what a (mostly) API-compatible, non-node-based
More informationby Pearson Education, Inc. All Rights Reserved. 2
An important part of every container is the type of iterator it supports. This determines which algorithms can be applied to the container. A vector supports random-access iterators i.e., all iterator
More informationCSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation
CSCI-1200 Data Structures Spring 2018 Lecture 8 Templated Classes & Vector Implementation Review from Lectures 7 Algorithm Analysis, Formal Definition of Order Notation Simple recursion, Visualization
More informationCSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists
CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists Review from Lecture 9 Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately,
More informationC++: Overview and Features
C++: Overview and Features Richard Newman r.newman@rdg.ac.uk Room CS127 2003-12-11 Programming & Design, 2003 1 Introduction You have: used streams seen how classes are used seen some C++ code Today: good
More informationTrees. Chapter 6. strings. 3 Both position and Enumerator are similar in concept to C++ iterators, although the details are quite different.
Chapter 6 Trees In a hash table, the items are not stored in any particular order in the table. This is fine for implementing Sets and Maps, since for those abstract data types, the only thing that matters
More information7 TEMPLATES AND STL. 7.1 Function Templates
7 templates and STL:: Function Templates 7 TEMPLATES AND STL 7.1 Function Templates Support generic programming functions have parameterized types (can have other parameters as well) functions are instantiated
More informationSETS AND MAPS. Chapter 9
SETS AND MAPS Chapter 9 The set Functions Required methods: testing set membership (find) testing for an empty set (empty) determining set size (size) creating an iterator over the set (begin, end) adding
More information19.1 The Standard Template Library
Chapter 19: The Template Library From a review of Effective STL : 50 Specific Ways to Improve Your Use of the Standard Template Library by ScottMeyers: It s hard to overestimate the importance of the Standard
More informationFunction Templates. Consider the following function:
Function Templates Consider the following function: void swap (int& a, int& b) { int tmp = a; a = b; b = tmp; Swapping integers. This function let's you swap the contents of two integer variables. But
More informationMakefiles Makefiles should begin with a comment section of the following form and with the following information filled in:
CS 215 Fundamentals of Programming II C++ Programming Style Guideline Most of a programmer's efforts are aimed at the development of correct and efficient programs. But the readability of programs is also
More informationAdvanced Programming in C++ Container Design I
Advanced Programming in C++ Container Design I This is an exercise on container design, especially in the view of robustness, iterators, and storage management. The container will be developed step-by-step,
More informationTraversing Trees with Iterators
Steven J. Zeil June 25, 2013 Contents 1 Iterating over Trees 4 1.1 begin()..................................... 6 1.2 operator++................................... 7 2 Iterators using Parent Pointers 11
More informationTraversing Trees with Iterators
Steven J. Zeil June 25, 2013 Contents 1 Iterating over Trees 3 1.1 begin()................................................................ 5 1.2 operator++..............................................................
More informationCSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators
Review from Lecture 7 CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators, and destructors
More informationCSE 333 Midterm Exam Cinco de Mayo, 2017 (May 5) 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 informationvector<int> second (4,100); // four ints with value 100 vector<int> third (second.begin(),second.end()); // iterating through second
C++ Vector Constructors explicit vector ( const Allocator& = Allocator() ); explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() ); template vector (
More informationArrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors
Arrays Returning arrays Pointers Dynamic arrays Smart pointers Vectors To declare an array specify the type, its name, and its size in []s int arr1[10]; //or int arr2[] = {1,2,3,4,5,6,7,8}; arr2 has 8
More informationCSE100. Advanced Data Structures. Lecture 4. (Based on Paul Kube course materials)
CSE100 Advanced Data Structures Lecture 4 (Based on Paul Kube course materials) Lecture 4 Binary search trees Toward a binary search tree implementation using C++ templates Reading: Weiss Ch 4, sections
More informationPIC 10A Objects/Classes
PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous
More informationImplementing an ADT with a Class
Implementing an ADT with a Class the header file contains the class definition the source code file normally contains the class s method definitions when using Visual C++ 2012, the source code and the
More informationUniversity 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 Summer 2005 3:00pm 4:15pm Tuesday, July 5 Name: NetID: Lab Section
More informationQUIZ. What are 3 differences between C and C++ const variables?
QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,
More informationLAB 5, THE HIDDEN DELIGHTS OF LINKED LISTS
LAB 5, THE HIDDEN DELIGHTS OF LINKED LISTS Questions are based on the Main and Savitch review questions for chapter 5 in the Exam Preparation section of the webct course page. In case you haven t observed
More informationCSCI-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 informationSTL: C++ Standard Library
STL: C++ Standard Library Encapsulates complex data structures and algorithms CSC 330 OO Software Design 1 We ve emphasized the importance of software reuse. Recognizing that many data structures and algorithms
More informationBasic Array Implementation Exception Safety
Basic Array Implementation Exception Safety CS 311 Data Structures and Algorithms Lecture Slides Monday, October 26, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks
More informationPrefix Trees Tables in Practice
Prefix Trees CS 311 Data Structures and Algorithms Lecture Slides Friday, December 7, 2007 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005
More informationCSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators
CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators Review from Lecture 7 Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators, and destructors
More informationLecture 10 Notes Linked Lists
Lecture 10 Notes Linked Lists 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning, Rob Simmons, André Platzer 1 Introduction In this lecture we discuss the use of linked lists to
More informationSlide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary
Slide Set 14 for ENCM 339 Fall 2015 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary Fall Term, 2015 SN s ENCM 339 Fall 2015 Slide Set 14 slide
More informationLab 6 Vectors and functions
CMSC160 Intro to Algorithmic Design Blaheta Lab 6 Vectors and functions 11 October 2016 The drill for this lab is another part of the Chapter 4 drill. Come to lab on Tuesday either with it completed or
More informationLecture-5. STL Containers & Iterators
Lecture-5 STL Containers & Iterators Containers as a form of Aggregation Fixed aggregation An object is composed of a fixed set of component objects Variable aggregation An object is composed of a variable
More informationPointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple
More informationThe Structure of a C++ Program
Steven Zeil May 25, 2013 Contents 1 Separate Compilation 3 1.1 Separate Compilation.......... 4 2 Pre-processing 7 2.1 #include.................. 9 2.2 Other Pre-processing Commands... 14 3 Declarations
More informationThese are notes for the third lecture; if statements and loops.
These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern
More informationUnit 1: Preliminaries Part 4: Introduction to the Standard Template Library
Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library Engineering 4892: Data Structures Faculty of Engineering & Applied Science Memorial University of Newfoundland May 6, 2010 ENGI
More informationCSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists
Review from Lecture 8 CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists Designing our own container classes Dynamically allocated memory in classes Copy constructors, assignment operators,
More informationLecture 10 Notes Linked Lists
Lecture 10 Notes Linked Lists 15-122: Principles of Imperative Computation (Summer 1 2015) Frank Pfenning, Rob Simmons, André Platzer 1 Introduction In this lecture we discuss the use of linked lists to
More informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing Traits and Policies Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 11. Juli 2017
More informationThe following is an excerpt from Scott Meyers new book, Effective C++, Third Edition: 55 Specific Ways to Improve Your Programs and Designs.
The following is an excerpt from Scott Meyers new book, Effective C++, Third Edition: 55 Specific Ways to Improve Your Programs and Designs. Item 47: Use traits classes for information about types. The
More informationPointers and References
Steven Zeil October 2, 2013 Contents 1 References 2 2 Pointers 8 21 Working with Pointers 8 211 Memory and C++ Programs 11 212 Allocating Data 15 22 Pointers Can Be Dangerous 17 3 The Secret World of Pointers
More informationCSE 333 Final Exam 3/19/14
Name There are 8 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, closed
More informationPIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics
PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.
More informationCS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych
CS125 : Introduction to Computer Science Lecture Notes #38 and #39 Quicksort c 2005, 2003, 2002, 2000 Jason Zych 1 Lectures 38 and 39 : Quicksort Quicksort is the best sorting algorithm known which is
More informationShort 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 informationCSCI-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 informationPractice Problems CS2620 Advanced Programming, Spring 2003
Practice Problems CS2620 Advanced Programming, Spring 2003 April 9, 2003 1. Explain the results of each vector definition: string pals[] = "pooh", "tigger", "piglet", "eeyore", "kanga" a) vector
More informationVector and Free Store (Pointers and Memory Allocation)
DM560 Introduction to Programming in C++ Vector and Free Store (Pointers and Memory Allocation) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides
More informationSixth lecture; classes, objects, reference operator.
Sixth lecture; classes, objects, reference operator. 1 Some notes on the administration of the class: From here on out, homework assignments should be a bit shorter, and labs a bit longer. My office hours
More informationContainer Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11
Di erent Kinds of Containers Container Notes A container is an object that stores other objects and has methods for accessing the elements. There are two fundamentally di erent kinds of containers: Sequences
More informationCSE 100: C++ TEMPLATES AND ITERATORS
CSE 100: C++ TEMPLATES AND ITERATORS Announcements iclickers: Please register at ted.ucsd.edu. Start ASAP!! For PA1 (Due next week). 10/6 grading and 10/8 regrading How is Assignment 1 going? A. I haven
More informationVariables. Data Types.
Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting
More informationCS201 - 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 informationThe Dynamic Typing Interlude
CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,
More informationSneaker Documentation
Sneaker Documentation Release 0.3.1 Yanzheng Li August 13, 2016 Contents 1 Overview 1 2 Get Started 3 3 Content 5 3.1 Build and Installation.......................................... 5 3.2 C Utilities.................................................
More informationSoftware Design and Analysis for Engineers
Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 4 Date:
More informationLab 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 information6.096 Introduction to C++
MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. 6.096 Lecture 3 Notes
More informationCSE 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 informationWhen we program, we have to deal with errors. Our most basic aim is correctness, but we must
Chapter 5 Errors When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with incomplete problem specifications, incomplete programs, and our own errors. When
More informationStandard Containers Library (1)
TDDD38 APiC++ Standard Library Containers 211 Standard Containers Library (1) C++ containers are objects that store other objects data structures. controls allocation and deallocation of the stored objects
More informationCSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists
CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists Review from Lecture 9 Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately,
More informationCSCI-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 informationCSCE 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 informationCS11 Advanced C++ Fall Lecture 1
CS11 Advanced C++ Fall 2006-2007 Lecture 1 Welcome! ~8 lectures Slides are posted on CS11 website http://www.cs.caltech.edu/courses/cs11 ~6 lab assignments More involved labs 2-3 week project at end CS
More informationBinary Search Trees. Contents. Steven J. Zeil. July 11, Definition: Binary Search Trees The Binary Search Tree ADT...
Steven J. Zeil July 11, 2013 Contents 1 Definition: Binary Search Trees 2 1.1 The Binary Search Tree ADT.................................................... 3 2 Implementing Binary Search Trees 7 2.1 Searching
More informationLecture 7. Log into Linux New documents posted to course webpage
Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next
More informationCS24 Week 3 Lecture 1
CS24 Week 3 Lecture 1 Kyle Dewey Overview Some minor C++ points ADT Review Object-oriented Programming C++ Classes Constructors Destructors More minor Points (if time) Key Minor Points const Motivation
More informationCE221 Programming in C++ Part 1 Introduction
CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab
More informationAssignment 1: grid. Due November 20, 11:59 PM Introduction
CS106L Fall 2008 Handout #19 November 5, 2008 Assignment 1: grid Due November 20, 11:59 PM Introduction The STL container classes encompass a wide selection of associative and sequence containers. However,
More informationCS197c: Programming in C++
CS197c: Programming in C++ Lecture 2 Marc Cartright http://ciir.cs.umass.edu/~irmarc/cs197c/index.html Administration HW1 will be up this afternoon Written assignment Due in class next week See website
More informationCSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists
Review from Lecture 8 CSCI-1200 Data Structures Fall 2013 Lecture 9 Iterators & Lists Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately, erasing items
More informationCSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation
CSCI-1200 Data Structures Fall 2018 Lecture 7 Templated Classes & Vector Implementation Announcements Lab 3 was a Frankenstein assembly of a new group exercise with part of a gdb lab. I hear many of you
More informationCSCI 102L - Data Structures Midterm Exam #2 Spring 2011
CSCI 102L - Data Structures Midterm Exam #2 Spring 2011 (12:30pm - 1:50pm, Thursday, March 24) Instructor: Bill Cheng ( This exam is closed book, closed notes, closed everything. No cheat sheet allowed.
More informationSplicing Maps and Sets (Revision 1)
Document number: N3645 Date: 2013-05-04 Project: Programming Language C++ Reference: N3485 Reply to: Alan Talbot cpp@alantalbot.com Howard Hinnant howard.hinnant@gmail.com James Dennett jdennett@google.com
More informationCS 216 Fall 2007 Midterm 1 Page 1 of 10 Name: ID:
Page 1 of 10 Name: Email ID: You MUST write your name and e-mail ID on EACH page and bubble in your userid at the bottom of EACH page including this page and page 10. If you do not do this, you will receive
More informationThe Standard Template Library Classes
The Standard Template Library Classes Lecture 33 Sections 9.7, 9.8 Robb T. Koether Hampden-Sydney College Wed, Apr 23, 2014 Robb T. Koether (Hampden-Sydney College) The Standard Template Library Classes
More informationOperator Overloading
Steven Zeil November 4, 2013 Contents 1 Operators 2 1.1 Operators are Functions.... 2 2 I/O Operators 4 3 Comparison Operators 6 3.1 Equality Operators....... 11 3.2 Less-Than Operators...... 13 1 1 Operators
More informationl 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 informationChapter 1: Object-Oriented Programming Using C++
Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms
More information