CS 106B Class Notes
CS 106B Class Notes
Marty Stepp
CS 106B
Class Notes
Lecture 1 - 03/30/2015
Get Qt creator
Int main() {
Return 0 }
Lecture 2 - 04/01/2015
#include
<libraryname>: Use the C++ library:
libraryname.h : Uses the local directory library
Use <iostream> at beginning of program
<cmath> has common math functions
Using namespace std;
Allows for certain commands
Cout - console output
Use << to enclose what you want to print. Also use << to enclose
variables;
Endl - end line Better style than \n.
Cout << hi my age is << age << ok << endl;
Cin >> variable
Reads input from console and stores it in the given variable
Uses >> (!!!)
Often preceded by a prompt that explains to the user what it ask
s for.
#include simpio.h
getInteger(prompt)
getReal(prompt)
getLine(prompt)
Parameters send info into a method, return takes info out.
These libraries restrict what data types are allowed for paramet
ers
Comments: Use /* and */.
Functions: Saves some code, exits upon hitting return statement.
Type name(type name, parameters, etc...){
Statement;
Statement;
Return expression; //if return type is something other than voi
d
}
Call: name(parameters)
IMPORTANT: Order of declaration is very important.
Function prototype: Write heading of function at very top ( I prom
ise the function exists )
Heading is everything before {}. Put a semicolon after.
Value semantics: If primitive data types are passed, values are copied.
Reference Semantics: Attach a & after the data type, which links the inp
ut parameter to variable under nother method.
Can be used to write a swap function.
You can also pass the parameter as a data type
Benefits: Return more than one values, store the value directly
into the parameter.
Downsides: Hard to tell, slower than value, can't declare a lite
ral value.
Strings: #include <string>
string s = "hello"
s[k] or s.at(k) get the character at index k.
#include "stack.h"
has stack.size() and stack.isEmpty()
stacks are printed horizontally
To find all elements in the stack....
DONT use for loop. Use while loop, then s.pop().
Be careful when passing by reference, because stack can get dest
royed.
queue - Only accessible element is the earliest added
Implemented like a linked list.
First in, first out (FIFO)
You can only add (enqueue) to the back
You can only examine/remove (peek/dequeue) from the front
Uses: operating system functions such as printing.
Helps to loop through with while(!queue.isEmpty()) as queue size
can change.
You can combine the two to reverse file contents.
Lecture 06 - 04/10/2015
Set: A collection of unique values.
Use: Counts the number of unique words in a large text file.
while (input >> word): Can grab all words in an input stream.
Allows for add, remove, search(contains), size, isEmpty
HashSet: Implemented using a special hash table
Very fast, but elements are stored unpredictably.
Set: Implemented using linked binary tree
Slower, but ordered list, in some way.
You can add, equate, intersect, differ sets.
for-each loop is a clean way to run over a Vector/Set
Map: A collection of PAIRS (key/value) in association with each other.
Linked so easy to find value given the key.
put(k,v) adds to the map
get(k)/remove(k) finds/removes value associated with the key.
The index (key) doesn't have to be an integer.
i.e. Map<string, int> name;
map[key] == value and map[key]++
Compound Collections: Collections of Collections
Vector<Set<int> > //include space to help compiler.
Use: We can find anagrams of a word in a dictionary.
Map<string, Set<string> >.
Lecture 07 - 04/13/2015
Recursion
Definition in terms of itself
Powerful when considering iterations
Some programming languages use exclusively recursion ('functiona
l programming')
Divide into base case and recursive case (think: "How is my prog
ram self-similar?")
Not too much slower than regular loops
Throwing exceptions
throw "expression" generates an error message
#include "error.h"
Lecture 08 - 04/15/2015
Moar recursion
Palindrome, binary, etc...
optional parameter (string word = "")
if not given, then it skips it no problem
Lecture 09 - 04/17/2015
Can help stop the program early if you want one solution.
Classes: If you want to a data type to hold a new format (date, for exam
ple)
Class: Template for new objects. Create your own class or object
!
Abstraction hides the implementation of object from the user.
private instance variables, public constructors and methods.
C++: You need a .h (header) file and a .cpp file (implementation)
header: only interface and declaration of what you have in your
class.
#ifndef _name_h
#define _name_h (protection against multiple .cpp to in
clude this)
class Name {
public:
Name(param)
Type name(param)
Type name(param)
private:
type name
type name
};
//semicolon is really important!
private variables are very important (encapsulated) protects int
erface and integrity.
implementation: source file containing definitions.
Constructor creates the objects.
Date::name(param)
Add const after a header to inform that state does not change.
Every object will have a copy of the methods
Member functions, in other words, is encapsulated within
the object
Operator overloading
redefine the behavior of a common operator.
declare it in the .h file.
returnType operator <op>(parameters)
//yay, easy!
Lecture 13 - 04/27/2015
Operator overloading: Don't abuse
put operators towards the end of the header file.
const refers to whether it can change or not. (with overloaded o
ps)
Useful: To make it printable... //returns a reference to the str
eam so it can be chained.
ostream& operator <<(ostream& out, Type& name) {
statements;
return out;
}
friend can allow a public method to access private data.
Implementing a collection: Vector-like
First, arrays.
type* name = new type[];
referred to by Vector with a pointer.
type* name = new type[](); //initialized to have all e
lements zero.
memory must be free to avoid a MEMORY LEAK
delete[] name;
ArrayList: add(value), get(index), size(), remove(index), indexOf(value)
, toString();
}
LinkedList class
Implemented exactly like ArrayList and Vector
starts with a pointer called 'front'
to avoid falling off the edge, check (current->next != NULL)
one way to change is front = ____;
another is ____->next = ____;
get
Use a for loop to traverse current through indices
return current->data
insert
traverse i-1 nodes
create a temporary new node that points to the latter half, then
add it to the front.
if index passed is zero (front), create copy of old front and re
assign.
Lecture 16 - 05/04/2015
Freeing memory
new - stores a memory address that is preserved after function
Whenever there's a "new" we need a "delete" afterwards
put after individual constructors, or create a ~destructor to fr
ee all nodes.
Next assignment: PRIORITY QUEUE
Sometimes there's an urgency (printers with different access lev
els).
Provides fast access to highest priority element.
enqueue, dequeue, peek, peekPriority, isEmpty, size, toString, c
hangePriority, clear,
How to implement?
1) We can represent PQ as a Vector.
This however, has enqueue runtime of O(1), but d
equeue/peek runtime of O(N).
2) Maybe a sorted Vector?
Enqueue now has runtime of O(N), dequeue has run
time of O(N) due to remove and shift, but peek runs O(1).
3) Linked List
Value as a string, priority as an int.
Sorted: Dequeue/peek is now O(1), but
IMPLEMENT: Unsorted array, Sorted linked list, and Heap.
Heap: An arrangement of elements in an array.
start, or 'root' index is 1.
Every index has a "parent" index (i/2) and two "children" indice
s (i*2, i*2+1).
Add it at the first empty index, but then swap up until it is at
right index.
Adding has runtime of O(log(N)), peek has const runtime
remove: put last element into first, then bubble BACKWAR
DS (runtime O(log(N))).
Lecture 17 - 05/06/2015
Bogo sort: Shuffle until it's completely sorted. Average runtime = O(N!)
, worst case INFINITY
Quantum sort: Multiple parallel universes, runtime O(1).
Selection sort: Store a minIndex and scan through i,j to find minIndex a
s you go. Runtime O(N^2).
Insertion Sort: Take successive elements and group them into the previou
s sublists. Runtime O(N^2) but slightly faster than selection.
Merge Sort: Divide data in half, sort each half, and then combine sorted
halves. Recursively, runtime O(N logN).
ession.
Guarantees a find, should it exist, and returns first one.
Breadth-first search: Explore each level of connection among all possibl
e paths.
Will always find shortest possible path.
Word-Ladder!
In general, DFS uses less memory for storage than BFS. Runtime O(V + E).
Dijkstra's Algorithm: Finds the MIN WEIGHT path in a graph.
General: Create a table that keeps track of best path to a curre
nt vertex and updates.
Pseudocode: Initialize with every vertex at INFTY except V1, whi
ch is 0
Load into a PriorityQueue and dequeue ea
ch vertex to be visited.
if (V = Vn), done!
if (cost < n's cost) update cost;
Each vertex can also store a weight and a previous vertex.
Helps to backtrack once you reach the final destination.
Lecture 23 - 05/20/2015
More graphs!
Common bugs with Dijkstra's - Update the PQ! and make sure mark/unmark i
s done correctly
A* Search: Similar to Dijkstra's
heuristic: A speculation, estimation, or educated guess that gui
des the search.
example: On Google Maps, take the straight line distance
as estimate.
admissible: NEVER overestimate (or else things might blo
w up).
key difference: Run Dijkstra from a -> b, BUT add a heuristic fr
om b -> c as you run the algorithm.
pqueue := (vi, at priority H(vi, v2)).
!!!Make sure to compute cost separately when updating.
add heuristic only when updating priority on rec
ursive call
Lecture 24 - 05/22/2015
Spanning trees: A set of edges that connects all vertices with no cycles
.
Minimum spanning tree (MST): lowest combined edge weight (cost).
Kruskal's algorithm: Finds a MST in a given path (guaranteed)
Remove all edges from the graph.
Place all edges into a priority queue based on their weight
while (PQ is not empty)
Dequeue an edge from PQ
If edge's endpoints are NOT already connected, add to gr
aph (!!!This is kinda hard)
otherwise do nothing
Able to make mazes (remove walls until vertices and edges form M
ST)
When implementing....
cluster: group of vertices that are connected.
now just figure out if two vertices are in the same clus
ter
must be able to MERGE clusters.
Graph implementation
Vertex? edges? paths?
Method 1: edge list - an unordered list of all edges in the grap
h
Vertices are implicitly contained in the set of edges.
Fast for printing out all neighbors
Method 2: adjacency list - lists of each vertex's neighbors
Fast for finding all neighbors of a vertex.
Method 3: adjacency matrix - NxN matrix where the weight of each
edge is the a[i,j] entry.
row is start, column is the ending vertex.
Underlying representation is comprised of many Maps.
Lecture 25 - 05/27/2015
Hash Implementation
Set: Could be done with array or sorted array
Strange idea: What if we stored every value i at index i?
Well, other than memory/sparseness, it works pretty darn fast
Hash idea: Store any given element value at a specific index.
Hash function: Mapping process from index to values.
To improve our strange idea...group terms into buckets of mods.
buuuut...what if you add two values with same value % 10?
probing: resolve a collision by shifting it to another i
ndex.
separate chaining: create a list at each index storing a
ll values
rehash: When table is too full, just grow to a larger array
load factor: ratio of # elements / hash table length
Lecture 26 - 05/29/2015
INHERITANCE: A hierarchy of related classes.
One class EXTENDS another class, absorbing its data/behavior
Superclass: parent/base class where everything begins
Subclass: The class that extends from the superclass
Gets everything superclass have.
Example: The Trailblazer world classes.
Example of Inheritance: Create an "Employee.cpp" superclass.
Then extend into "Lawyer," "Programmer," etc...
Subclasses must inherit EVERYTHING.
However, methods can be overwritten in the subclass
"virtual" keyword must be declared in superclass -- might as wel
l make all methods virtual then! (no problem)
header in subclass is the same. Just different .cpp implementati
on.
To call superclass method, write "Superclass::method()" anywhere
.
Subclasses are still forbidden to directly access private variables of s
uperclasses.
Workarounds: Create a public "setField()" method
or subclass_Constructor(params) : superclass_Constructor
(params)
^initialization list
Superclasses can now implement methods that only belong to the subclass
Example: Lawyer can have a "sue" method.
Multiple Inheritance: One subclass has multiple superclasses
Example: iostream is a subclass of istream and ostream.
Private Inheritance: A subclass inherits a superclass but cannot tell ex
ternally
class Name : private SuperclassName
POLYMORPHISM: You can create a superclass object that belongs to a subcl
ass