Search
Create
Log in
Sign up
Log in
Sign up
CS 2150 Part 3
STUDY
Flashcards
Learn
Write
Spell
Test
PLAY
Match
Gravity
Terms in this set (154)
constant reference
const type & name
used when an object should not be modified
IEEE 754 Floating Point Single Precision (32 Bits):
1 sign bit
8 exponent bits (subtract 127)
23 mantissa bits
array1 = array2
Not allowed!
an array variable is...
A pointer to the first element of the array
Multi-dimensional arrays:
int m[3][4]; (3 rows, 4 columns)
When are trees not good to use?
When the items do not have a sorted order
When we want less complexity
When we want constant time operation on retrieves
When we want constant time for all operations
What is splaying?
...
Linear probing, quadratic probing, and double hashing are all examples of:
Open Addressing
Why should you never use vectors for separate chaining?
Lots of unused cells
Something that is private in the super class is ____ in the subclass
inaccessible
IBCM Special Purpose Registers
IR (Instruction Register) - stores bits which encode an instruction
PC (Program Counter) - stores an address of an instruction
IBCM: Load
Load memory from address into accumulator
IBCM: store
store accumulator into memory
IBCM: add
add accumulator value and value in address
IBCM: sub
subtract accumulator value and value in address
IBCM: and
logical AND
IBCM: or
logical OR
IBCM: xor
logical XOR
IBCM: not
logical NOT
IBCM: nop
literally do nothing
IBCM: jmp
jump to address
IBCM: jmpe
jump to address if accumulator equals zero
IBCM: jmpl
jump to address if accumulator is less than zero
IBCM: brl
jump to address; set accumulator to the value of the program counter just before the jump
Assembly: Move
mov <dest>, <src>
Assembly: push
push <op>
-decrements rsp by 8 (stack grows down)
-operand moved onto stack
Assembly: pop
pop <op>
-pops top element of stack to memory or register, incremenets stack pointer by 8
Assembly: lea
lea <op1>, <op2>
Place address of second parameter into the first parameter
Assembly: add/sub
add <op1>, <op2>
adds or subtracts (storing in first register)
Assembly: inc/dec
inc <op>/dec <op2>
Increases or decreases by 1
Assembly: imul
imul <op1>, <op2>
Multiplies numbers, storing in first operand
Assembly: idiv
idiv <op1>,<op2>
Divides numbers, storing in first operand
Assembly: and/or/xor
and/or/xor <op1>,<op2>
Performs bitwise comparison, then stores in first
Assembly: jmp
jmp <label>
Jumps to the label
Assembly: cmp
cmp <op1>,<op2>
sets machine status word - must be used before conditional jumps
Assembly: je
jump when condition equal is set
Assembly: call
call <label>
Pushes address of the next instruction onto stack, then jumps to label
Assembly: ret
Pops the return address from the stack, then jumps to that address
Assembly: return value goes in the
rax register
Registers for parameter passing:
rdi, rsi, rdx, rcx, r8, r9
Registers which may be modified by the callee (without pushing/popping):
r10, r11
Registers which may not be modified by the callee (without pushing/popping):
rbx, rbp, r12-r15
Pointer pointing to the top of the stack
rsp
Caller-saved registers
r10, r11, and registers used for parameters if need value saved
Caller rules (Prologue)
1. Save Caller-saved registers
2. Prepare parameter registers and stack
3. Call subroutine
Caller rules (Epilogue)
1. Remove parameters if on stack
2. Return value
3. Restore caller-saved registers
Callee rules (Prologue)
1. Allocate local variables
2. Save callee-saved registers
Callee rules (Epilogue)
1. Return value saved to rax
2. Restore callee-saved registers
3. Deallocate local variables
4. Return
Activation record
All the things that are pushed onto the stack when a subroutine is called. Includes:
Registers
Parameters
Local variables
return address
Dynamic memory goes on the
heap
Static memory goes on the
stack
creating a class "Contact" which is a subclass of the class "Name"
class Contact: public Name {};
Subclasses inherit:
-data members defined in the parent class
-member functions of the parent class
-same initial data layout as the base class
Inheritance constructors
C++ calls parent constructor then child constructor
Inheritance destructors
C++ calls child destructor then parent destructor
c++ class with multiple inheritance
class Sphere: public Shape, public Comparable, public Serializable {};
Static dispatch
Decision on which member function to invoke made using compile-time type of an object
Dynamic dispatch
Decision on which member function to invoke made using run-time type of an object
Dynamic dispatch keyword
virtual
When calling a method from a pointer, C++ will base what subroutine to call off of...
the type of the pointer
virtual keyword
Used in parent classes - tells C++ "check for a subclass method to run before defaulting to parent method"
Whenever you use the virtual keyword, your object size
increases by 8 bytes
How to make an abstract class
Define functions like this: virtual returnType funcName() = 0;
pure virtual function
Function of the form: virtual returnType funcName() = 0;
if a class has a pure virtual function, then it....
cannot be instantiated
How would you implement a java interface in c++?
class with all pure virtual methods
Does a subclass need to define the method body of everything it inherits?
Only if it wants to be instantiated as the relevant superclass
Replicated vs shared
Replicated - where a grandparent class has two "instances" for the subclass
Shared - where a grandparent class is shared between parents, but has only one "instance" for the subclass
Between replicated and shared, in c++, ______ is the default
replicated
Shared inheritance can be specified by...
using the keyword virtual: class parent: public virtual grandparent1, public grandparent2{}
class child: public virtual parent1, public virtual parent2{}
Four types of multiple inheritance
Shared, replicated, non-replicated ("I won't deal with this"), Mix-in ("faking it" through interfaces)
Move constructor
-used to copy something from y that is about to go out of scope to x that is not
-avoid deep copying - just moves the pointer over (and prevents out of scope)
Some features of C++11
-Range-based for loops
-Move constructors
-uniform initialization
-smart pointers
PriorityQueue operations
insert, findMin, deleteMin
-inserts WITH A PRIORITY
Is a Binary Heap a Binary Search Tree?
NO
Binary heaps are useful for implementing
a priority queue
Perfect binary tree
all leaf nodes at the same depth, all internal nodes have two children
Full binary tree
each node has exactly zero or two children
Heap Structure Property
almost complete - completely filled, with the possible exception of the bottom level, which is filled left to right
Why is the "almost complete" property of a binary tree important?
So it can be represented in an array
Heap Ordering Property
The key in any node's parent is less then the key in the node.
Heap Insert
1. Put value at "next" leaf position
2. Repeatedly exchange node with its parent if needed
Heap DeleteMin
1. Remove root
2. Put "last" node at root
3. Find smallest child
4. Swap node with smallest child if needed
5. Repeat 3&4 if needed
How to use a heap to sort
1. Create a heap
2. Insert all your elements
3. Remove all your elements
Stable sort
If two things sort to the same spot, then their order relative to each other should be whatever it was before
Compression ratio
original num of bits / compressed num of bits
prefix code
no code in our encoding is a prefix of another code
Cost of a file encoded using huffman encoding
Cost = sum of frequency*bit-length of each character's encoding
Huffman encoding: (Steps)
1. Create a min-heap
2. Insert all symbols, ranked by frequency
3. Remove two symbols from the tree - combine them into a single node ("A or B"), with appropriate child nodes, and put that back onto the heap
4. When there are only two left, combine these into a tree (make them children of a root node)
ASCII is... (bits)
8 bits - 7-bit encoding plus one parity bit
Unicode is....
16 bits
Nodes consist of:
a set of nodes and a set of edges
directed acyclic graph
no cycles, directed
strongly connected graph
there is a directed path from every vertex to every other vertex
weakly connected graph
underlying unconnected graph is connected
Adjacency matrix
Method of representing a graph - each cell contains a cost
Adjacency list
Method of representing a graph - it's a linked list.
Problem with adjacency list
Linear lookup (compared to constant time lookup for adjacency matrix)
Problem with adjacency matrix
Uses a lot of memory
Topological sort
Given a directed acyclic graph, construct an ordering of the vertices such that, if there is a path from A to B, then A appears before B in the ordering
indegree of node v
number of edges going into node v
Topological sort pseudocode
-look for a node with indegree 0; print it
-decrease indegree of all subsequent nodes
-repeat
big theta of topological sort
V+E
Three types of shortest path algorithms
Single pair, single source, all pairs
Single pair shortest path
shortest path from A to B
Single source shortest path
shortest path from A to anywhere else
All pairs shortest path
shortest path from any A to any B
weighted path length from A to B
sum of cost of all edges on path from A to B
unweighted shortest path
all weights are 1
Dijkstra's algorithm
1. Each node has a distance field, initialized as infinity
2. Start at a given vertex s; update s's distance to be 0
Repeat the following until each vertex has been visited:
3. Check each of the current vertex's nearby neighbors - update their distance, if lower than previous distance value
4. Visit a new vertex - whatever is the lowest-distance unvisited vertex.
Bellman-Ford
algorithm for negative-cost edges
Dijkstra's algorithm does not work for
negative cost edges
Traveling salesperson problem
Given a number of cities, and the costs of traveling from any city to any other, what is the least-cost round-trip route that visits each city exactly once and then returns to the starting city?
Hamiltonian path
a path in a connected graph that visits each vertex exactly once
Hamiltonian cycle
A hamiltonian path that ends where it started
Theta of traveling salesperson
Theta(n!)
NP-complete
no known efficient solution
TSP is....
NP-complete
heuristic
relatively efficient ways to get relatively efficient solutions
spanning tree
a subgraph of a given graph that contains every vertex of G and is a tree
Construct a spanning tree
-start with a graph
-remove an edge from each cycle
minimal-weight spanning tree
spanning tree with the minimal total weight
Prim's Algorithm
1. Pick a node as the root
2. Incrementally add edges that connect a "new" vertex" to the tree
- pick the edge (u,v) where (u is in the tree, v is not, and where the edge weight is the smallest of all edges (where us is in the tree and v is not)
Dijkstra's runtime
Theta(e log v)
Prim's runtime
Theta(e log v)
Kruskal's MST algorithm
-Pick an edge with the smallest weight - if its addition does not create a cycle, add it.
-Repeat until you have v-1 edges
Space required is known before program starts
static
Space required is not known before the program starts
dynamic
Dynamic memory can be placed
on either the stack or heap (but most often the heap)
stack grows
down
heap grows
up
alloca() (C)
used for lifetime scoped, size unknown at compile time
malloc() (C)
used for lifetime unlimited, size unknown at compile time
malloc (size_t size)
Returns an untyped pointer (can point to anything) - returns an address that is the location of at least requested size - returns null if there isn't enough space
heap directory management routine allocates space in two ways:
-fixed-size-blocks allocation
-buddy blocks
Buddy blocks
-memory takes up the next highest power of 2 bytes
Memory hierarchy
Smallest to largest:
CPU registers
Cache
"Main" Memory (RAM)
Disk
The bigger, the slower
Processor cycle
the time it takes to execute a simple instruction
Memory access time
the time it takes to access memory
memory cycle time
the time it takes to write to memory
Cache levels
-content at each level is a subset of the level below
Cache hit
address requested is in cache
Cache miss
address requested is not in cache
cache page size
the number of contiguous bytes that are moved into the cache at one time
temporal locality
if an item is referenced, it will tend to be referenced again soon
spatial locality
if an item is referenced, items whose addresses are close by will tend to be referenced soon
storage allocated by malloc is
reserved forever
reclaiming storage in c
void free(void *ptr);
memory leak
program fails to release memory when no longer needed
realloc()
changes the size of the memory object pointed to by ptr to the size specified by size
void *realloc(void ❉ptr, size_t size);
tail recursion
no work to do between subsequent recursive returns
Each object contains a pointer to the
virtual method table
virtual method table
-contains addresses to each method
Pointer rundown for virtual methods
-pointer to object
-then pointer to virtual method table
-then pointer to method itself
;