You are on page 1of 3

CS 12 NOTES (FEB 7)

VECTORS
- dynamically growing array

STRUCTURES IN C++ (public by default)


Sample:
struct Vector {
int *data;
int count;
int capacity;
};

void append(Vector &v // Vector *v, int elem) {


if(v.count == v.capacity) {
v.capacity *= 2;

int *new_array = new int[v.capacity];


}

for(int i = 0; i < v.count; i++) {


new_array[i] = v.data[i]
}

v.data = new_array;

delete[]

OR

(*v).data[(*v).size] = elem;
(*v).size = (*v).size + 1;

OR

v->data(v->size) = elem;
v->size = v->size + 1;
}

int main() {
Vector v;

v.data = new int[10];


v.count = 0;
v.capacity = 0;
}

CLASSES IN C++ (private by default)


- recipe
- object = instantiated class

Sample:
class Name {
private:
string firstName;
string middleName;
string lastName;
public:
Name(string first, string middle, string last);
string getFirstName();
void setFirstName(string first);
};

Name::Name(string first, string middle, string last) {


firstName = first;
middleName = middle;
lastName = last;
}

string Name::getFirstName() {
return firstName;
}

void Name::setFirstName(string first) {


firstName = first;
}

int main() {
Name n = Name("Jose", "", "");

MEMORY ALLOCATIONS
1. STACK
- local variabe function
- automatically deallocate when out of scope
2. HEAP
- 'new' operator
- manually deallocate
3. STATIC
- static
- global

CONSTRUCTORS
- function that is called on initialization (used when making a new class or
struct)
- same name as class

LINKED LIST
- container of nodes
- each node contains two some fields (data & index)

Sample Code: (NOT YET DONE)


struct Node {
int data;
Node *next;
};

struct LinkedList {
int count;
Node *head;
public:
LinkedList();
void add(int elem);
void print_all();
int get_count();
int first();
};

LinkedList::LinkedList() {
count = 0;
}

LinkedList::get_count() {
return count;
}

LinkedList::add(int elem) {
Node *n = new Node;

n->data = elem;
n->next = nullptr;

if (head == nullptr) {
head = n;
} else {
head->next = n;
}

head = &n;
count++;
}

int LinkedList::first() {
return head->data;
}

int main() {
LinkedList list;
}