Previous Lecture lect18

lect18, Thu 03/14

More or STL and final wrap-up

Correction from last time

C++ strings are NOT passed by reference. By default, they are passed by value, and you would need to use an & to be able to change the original string in a function.

Review

Remember the two main ways to initialize pointers:

   int *p;
   int num = 5;
   p = # // this pointer points to an item on the STACK

   int *p;
   p = new int; 
   *p = 5; // this pointer points to an item on the HEAP

What is an array?

An array is a list of elements, stored sequentially in memory. The array variable (i.e., its name) itself acts like a pointer to the first element in that array.

Except that you cannot change the value of that pointer: it’s illegal in C++ to change the memory address of an array (see an example on the slides).

Why should we care about how arrays are represented in memory?

Having elements stored sequentially allows us to use access different elements by using either a [] operator or pointer arithmetic. For example, arr[7] is equivalent to *(arr+7). Notice how we are able to access specific element by adding the size of our data types 7 times to the pointer to the first element of the array.

If I want to create 3 pointers to integers, is int* a, b, c; enough?

No! In fact, only a will actually be a pointer, and b and c will just be integers. Fix that by adding asterisks to b and c or using typedef

What are dynamic variables and how are they different?

Dynamic variables in C++ are variables that are created on the heap. They are created with the new keyword and have to be deleted with the delete keyword.

What does it mean to delete a variable? How does that work?

Let’s look at an example. Box* b1 = new Box{ {50,40}, 20, 50}; We have just created a Box on the heap. This means that memory was allocated on the heap for the box b1. If you are interested in how much memory was allocated, you can calculate that by adding all the sizes of member variables of the type Box.

## STL Vectors

STL vector is a c++ class from the standard template library that behaves like a linked list.

Vector have a flexible size and some nice built-in functions.

To use vectors:

Review the lecture slides to make sure you understand when it’s OK to use [].

More review!

str.size() returns an unsigned integer - length of a string cannot be negative, so use an unsigned int in the for loop

Again, what is the difference between Dynamic Arrays and Linked Lists?

Pointer diagrams will still be relevant for the final!

Deleting a dynamic array: delete[] d; deletes all of the elements in the array that d points to.

Review True/False questions on slides! *Answers: T F T F F