




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































vectors + grids
stacks + queues
sets + maps
Object-Oriented Programming
arrays
dynamic memory management
linked data structures
algorithmic testing analysis
recursive problem-solving
C++ basics
Diagnostic
real-world algorithms
Core Tools
User/client
Implementation
Today’s
question
Today’s
topics
○ We will only implement a subset of the functionality that the Stanford Vector provides. ○ OurVector can only store integers and is not be configurable to store other types ○ When we left off on Tuesday, OurVector was limited to storing a fixed number of elements. For now, if we run out space we just throw an error.
class OurVector { public: OurVector(); ~OurVector(); void add(int value); void insert(int index, int value); int get(int index); void remove(int index); int size(); bool isEmpty(); private: int* elements; int allocatedCapacity; int numItems; };
● The constructor is the special method that gets called when a new instance of a class is declared. In this method, we initialize all of our member variables to the appropriate values, including allocating any necessary memory. ○ The constructor for a class named ClassName has signature ClassName(args); ● The destructor is the special method that gets called when an instance of a class goes out of scope and thus is destroyed. In this method, we most often are responsible for freeing any dynamically allocated memory used by the instance. ○ The destructor for a class named ClassName has signature ~ClassName();
0 1 2 3 4 5 6 7
elements
allocated Capacity
numItems
0x1234abef
8
4
// client code OurVector vec; vec.add(106); vec.add(42); vec.add(-3); vec.add(27); vec.remove(1); vec.insert(0, 198);
● Hermit crabs are interesting animals. They live in scavenged shells that they find on the seafloor. Once in a shell, this is their lifestyle (with a bit of poetic license): ○ Grow until they have outgrown their current shell. Then, follow these 5 steps. ■ Find another, larger shell. ■ Move all their stuff into the new shell. ■ Leave the old shell on the seafloor. ■ Update their address with the Hermit Crab Postal Service. ■ Make note of their new shell's spacious capacity by posting on Hermit Crab Instagram. ● While this is purposefully a bit of a silly analogy, this process models almost exactly what we need to do in order to dynamically resize our internal data storage mechanism.
0 1 2 3
elements
allocated Capacity
numItems
0x1234abef
4
4
0 1 2 3
elements
allocated Capacity
numItems
0x1234abef
4
4
0 1 2 3
elements
allocated Capacity
numItems
0x1234abef
4
4
0 1 2 3 4 5 6 7
0 1 2 3
elements
allocated Capacity
numItems
0x1234abef
4
4
0 1 2 3 4 5 6 7