Lecture 5/11: Implementing VectorInt


May 11, 2020

đź“‚Associated files

Implementing VectorInt

CS 106B: Programming Abstractions

Spring 2020, Stanford University Computer Science Department

Lecturers: Chris Gregg and Julie Zelenski

An image of a hermit crab Hermit Crab (Pagurus bernhardus)


Slide 2

Announcements


Slide 3

Today's Goals:


Slide 4

Why do we care about delete?

const int INIT_CAPACITY = 1000000;

class Demo {
public:
    Demo(); // constructor
    string at(int i);
private:
    string *bigArray;
};

Demo::Demo()
{
    bigArray = new string[INIT_CAPACITY];
    for (int i = 0; i < INIT_CAPACITY; i++) {
        bigArray[i] = "Lalalalalalalalala!";
    }
}

string Demo::at(int i)
{
    return bigArray[i];
}
int main()
{
    for (int i=0;i<10000;i++){
        Demo demo;
        cout << i << ": " 
             << demo.at(1234) 
             << endl;
    }
    return 0;
}

Slide 5

What happened?

Demo::~Demo()
{
    delete[] bigArray;    
}

Slide 6

The VectorInt class implementation

An image showing a Vector with a bunch of numbers in it


Slide 7

Dynamic Memory Allocation: your responsibilities

A big W


Slide 8

Expansion Analogy: Hermit Crabs

An image of a hermit crab


Slide 9

Dynamic array expansion steps


Slide 10

Vector Expansion: Memory