In this lecture and the next, we'll implement a set (an associative container for storing unique elements) based on an array.
We'll be following our normal process for building an ADT - starting with our motivating use cases and the interface we want, followed by a fundamental data representation and invariants, and finally filling in the implementations for each member function.
1: An Array-Based Unsorted Set
Let's take a look at a data structure to represent an unsorted set. We'll be following our normal process for building an ADT - starting with our motivating use cases and the interface we want, followed by a fundamental data representation and invariants, and finally filling in the implementations for each member function. Our next step is to choose a data representation and invariants. This ends up as the foundation for the data structure, the implementation of its functions, and the efficiency we can achieve. Throughout the course, we'll end up looking at several different possibilities for an unsorted set. We'll start here with an unsorted array. |
2: Implementation
2.1
2.2
Let's get into the implementation of a default constructor and a few member functions for the array-based unsorted set.
2.1 Exercise:
IntSet::insert()
Implement the First, your code should call
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
2.2 Exercise:
IntSet::remove()
Below are some potential implementations of the It may be helpful to trace through the code on this set, removing the Or, you might also consider pasting them into the code for the exercise above and uncommenting the additional set of tests in Which of the implementations of
Two of the implementations above for You're welcome to check your solution with this walkthrough video: NOTE: For completeness, I'll mention here that ultimately both implementations that work correctly end up having similar runtime complexities in that their runtime scales linearly with the amount of elements in the set - that's because even though the one I describe in the walkthrough video does less work to remove the element, it still needs to call |
3: Member vs. Non-Member Operator Overloads
3.1
You know the only thing cooler than a set ADT? A set ADT with custom operators! We'll look at two different examples:
3.1 Exercise: Overloading
+= on IntSet
Let's add a
The
You're welcome to check your solution with this walkthrough video: |