Docsity

CPSC 223 Lecture 5: Pointers, Linked Lists, and Templates, Slides of Data Structures and Algorithms

Partial preview of the text

Download CPSC 223 Lecture 5: Pointers, Linked Lists, and Templates and more Slides Data Structures and Algorithms in PDF only on Docsity!

CPSC 223

Algorithms & Data Abstract Structures

Lecture 5: 

Pointers, Linked Lists, Templates

Today …

• Quiz 3

• Pointer refresher (cont.) [Sect. 4.1]

• Linked List refresher [Sect. 4.2]

• Basic C++ templates [Sect. 8.5]

• Next time:

  • More on inheritance and operators

• Readings

  • Sect: 8.5-8.

CPSC 223, Fall 2010 2

Pointer Refresher

  • For ordinary variables, the C++ compiler allocates

memory to hold the value

int x;

  • Assigning a value to the variable places the value in

the allocated memory space

x = 5;

CPSC 223, Fall 2010 3

memory loca;on @111 to hold an int

5

value placed in the memory loca;on @

Pointer Refresher

  • A pointer variable contains the location (or address )

of a memory location

int x;

int* xptr;

  • Assigning a value to the variable places the value in

the allocated memory space

x = 5; 

xptr = &x;

CPSC 223, Fall 2010 4

memory loca;on @

to hold an int

5

value placed in the

memory loca;on @

memory loca;on @

to hold an int address

@

x’s address placed in the

memory loca;on @

Pointer Refresher

  • We can also dynamically deallocate memory at runtime

using the delete keyword

int* xptr = new int;

*xptr = 5;

delete xptr;

xptr = NULL;

  • Deallocating memory helps avoid memory leaks!
    • When no variables in your program refer to some allocated

memory loca;on

  • This is bad because these leaks use up oSen needed space
  • We don’t want to run out of memory because of unused values!

CPSC 223, Fall 2010 7

value placed in the

memory loca;on @

@

x’s address placed in the

memory loca;on @

NULL^5

Pointer Refresher

Dereferencing objects and object pointers

Stock s1(“MSFT”, 1000);

Stock* s2 = new Stock(“GOOG”, 1000);

  • How do we call the getShares() func;on on s1 and s2?

s1.getShares(); // the “.” operator

(*s2).getShares(); // “long form”

s2->getShares(); // preferred “syntactic sugar”

  • “->” is the “ membership operator ”
    • If the variable is a structure ( object ), use the “.” operator
    • If the variable is a pointer ( to an object ), use “->” operator

CPSC 223, Fall 2010 8

Stock object

mem. loc. @

s

Stock object

mem. loc. @

s1 =

Linked Lists (Review)

CPSC 223, Fall 2010 9

List Operations

What are some common list operations?

  • Insert items into a list (add, insertAt)
  • Remove items from a list (remove)
  • Retrieve items from a list (get)
  • Check for an empty list (isEmpty)
  • Get the length of a list (getLength)

CPSC 223, Fall 2010 10

Remove

In HW2, we remove by position in the list

What will the list be after removing the item at position 1?

What if we try to remove from a position not in the list?

Nothing should be removed!

CPSC 223, Fall 2010 13

item next

head item2 tail next

item

item next

head (^) item3 tail

Retrieve

In HW2, we also retrieve by position in the list

What does retrieving from position 1 return?

item

What if we try to get an item from a position not in the list?

Nothing should be retrieved!

CPSC 223, Fall 2010 14

item next

head item2 tail next

item

Retrieve

In HW2, we define retrieve as follows:

bool get(int index, T& itemAtIndex) const;

  • Here is how we would call the get method:

Entry e;

if(list.get(1, e) == true)

cout << “The element at 1 is: ” << e << endl;

else

cout << “Index 1 is out of bounds” << endl;

Note itemAtIndex is not const, but is passed by reference!

CPSC 223, Fall 2010 15

e is serving as an output here !!!

Why design it this way?

Implementing Nodes

There are many ways we can design list nodes

  • In HW2, we’re taking the easy route … as a private struct

class List {

private:

struct Node {

T item;

Node* next;

Node* head;

Node* tail;

CPSC 223, Fall 2010 16

Node is a private structure

Only visible from within List A type variable

(templates)

Generic types

Most data structures work over any type of value

  • E.g., Lists can hold any type of item
  • A standard solution

typedef int ListItemType;

Do you see any problems with this approach?

  • Changing the type means changing the code …
  • What if we want one list of int and another list of Entry?

CPSC 223, Fall 2010 19

To change the item type,

change the typedef

C++ Class Templates

A class template allows you to declare type “parameters”

  • Like a variable that ranges over types

template

class Pair {

public:

Pair();

void setPair(T first, T second);

T getFirst() const;

T getSecond() const;

private:

T firstItem;

T secondItem;

};

CPSC 223, Fall 2010 20

Here “T” means any type

This means we can

create pairs over any

type of values

C++ Class Templates

Using our generic Pair class

int main()

Pair p1; // int pair

p1.setPair(3, 4);

Pair p2; // double pair

p2.setPair(7.5, 8.25);

Pair p3; // Stock pair

p3.setPair(Stock(“GOOG”,60), Stock(“MSFT”, 10));

CPSC 223, Fall 2010 21

C++ Class Templates

Defining methods

template

Pair::Pair() {}

template

void Pair::setPair(T first, T second)

{

firstItem = first;

secondItem = second;

}

template `

T Pair::getFirst() const

{

return first;

}

CPSC 223, Fall 2010 22

Annoying, but required!

Precede each method with

template declaration, and

Class Name ::

Operator Overloading

We can define the behavior of C++ operators when

applied to objects of a class

  • I/O functions with >> and <<
  • Assignment and copy replaced by =
  • Comparison (<, >, etc.)
  • Concatenation (+)
  • And so on

CPSC 223, Fall 2010 25

Operator Overloading

  • Does not let us alter the meaning of operators when

applied to built-in types (e.g., int, char, float, etc.)

  • At least one argument must be an object of a class
  • Does not allow us to define new operator symbols
  • overload only those provided for in the language
  • there are very specific rules/conventions as well

CPSC 223, Fall 2010 26

Operator Overloading

  • Similar to overloading functions
    • We are changing one or more of the arguments

For example, instead of: 

istream & operator>>(istream & in, char& ch)

We have:

istream & operator>>(istream & in, Key& key)

  • Arguments denote operands, return type the value

returned by the operator

CPSC 223, Fall 2010 27

Operator Overloading

  • Operator return values
    • the residual value of the expression containing that

operator and its operands

  • pay close attention to the type and value returned
  • returned value allows operator to be used in larger

expressions

  • … to be used as an operand in another operator 

(e.g., a + b + c)

CPSC 223, Fall 2010 28