Continuing from last time, we'll consider another potential implementation of a set, this time based on an underlying array that is kept in sorted order. The addition of a sorting invariant means some of our functions are more complicated (i.e. you can't just put elements wherever), but searching for elements in the array can be done much more efficiently.
We'll also introduce templates, which are a C++ mechanism for compile-time parametric polymorphism and can be used to implement generic containers with flexible element types (e.g. set<int>
or set<string>
).
But first, we'll cover a few miscellaneous topics that didn't fit in the last lecture:
++
and --
operators. Overloading operators with member functions (as opposed to regular, non-member functions).
1: Prefix
++ vs. Postfix ++
Ever wanted to know the difference between |
2: Member vs. Non-Member Operator Overloads
2.1
You know the only thing cooler than a set ADT? A set ADT with custom operators! We'll look at two different examples:
2.1 Exercise: Overloading
+= on IntSet
Let's add a
The
You're welcome to check your solution with this walkthrough video: |
3: A Sorted
3.1
IntSet
Let's make a key change to the fundamental strategy and data representation for our set - keeping all the elements in sorted order - and see if we can improve the performance of the data structure…
3.1 Exercise:
SortedIntSet::insert()
Implement the The You're welcome to check your solution with this walkthrough video: Note: This walkthrough uses several different files for the code, which is different than the above, where we had everthing embedded into one file. (The solution for |
4: Templates
4.1
Finally, let's use templates to implement a generic set container with a flexible element type.
4.1 Exercise:
fillFromArray() Function Template
Fill in the blanks to make the function work as intended (the
You're welcome to check your solution with this walkthrough video: |