You are on page 1of 12

lecture 2/27/13 passing vectors to functions erse,.

insert know how to make these functions for (int i = 0; i < v.size(); i++0) int slot = rand()% v.size(); overload < operator parallel vectors better to use a class midterm random number classes vectors overloading go thgouh slides do exams and problems class question for sure scope random seed get a number in range 25-50 and then multiply by 2 to get odd number random vector what is difference between default constructor and regular constructor? class implementation string bool student::operator>(student s) current instance of one student look at all the examples what element appears most frequently what if negative? to find max frequency, create frequency vector and then max that vector unique 2 10 4 2 2 2 10 4

discussion 2/28/13 divisible by 4 but not by 3 srand((int)(time(0))); for(int i=1, i<=100; i++) {int m = rand(); //generates random number while( m%4!=0 || m%3==0) //if random number not satisfying these conditions, c reate new number m = rand(); cout<<m; } vectors #include <vector> vector <data type> name(size); name; //gives you empty

avoid bounds error shuffle index1 = rand()%v.size(); index2 = rand()% v.size(); person +; classes class name{ public: name(); name( parameters ); member function private; }; midterm 2 winter 2012 twodice class data: dice1, dice2 constructor: default and with input member function twodice td1,td2 roll() td1,get_total() get_total(); td2.get_total() operator class TwoDice { public: TwoDice(); TwoDice(int d1, int d2); void roll(); int get_total() const; bool operator > (TwoDice d2); private: int dice1, dice2; bool TwoDice::operator > (TwoDice d2) int dice1, dice2; { return dice1+dice2 > d2.get_total(); or d2.dice1+d2,dice2; } throw two dices until the cumulative sum is odd on average how big is the sum? TwoDice d; int s=0 int sum = 0; for(i=1, i<=1000, i++) int sum=0; while(sum%2==0) { d.roll(); sum += d.get_total(); } s+=sum cout << (double)(s)/1000 //accessors make sure you put const, mutators

for (i = 0; i<= size-1; i++) { max = v[i]; for(j = i+1; j<==size-1; j++) index void sort(vector<int> %v) int max, index, t; for(i=0; i<=size-2; i++) { max = v[i]; index i: for(j = i+1; <=size-1; j++) if(v[j]>max) {max = v[j]; index = j; } t = v[i]; v[i] = v[index = max]; v[index] = t; } lecture 3/6/13 arrays always passed by reference when passing, remember to pass the length of the array in the separate variable double ave mean(ar,size) 2d arrays double table[3][4] 3 rows 4 columns row may not need to specify, but columns you have to for 2d just specify anyway file i/o cin and cout are stream objects define file stream objects for reading and writing from a file #include<fstream> ifstream fin; <<input stream object ofstream fout; int x fin >> x; read x from file fout << x; write x to fouts file fou.close(); writing to file if the file didnt exist, it will be created if it did exist, it will be overwritten if you want to append your stuff to the end use fout.open("myfile.txt", ios::app); its overloaded while(fin>>number) mynumbers.push_back(number); open() doesnt recognize strings - it looks for cstrings need to write fin.open(filename.c_str()); //converts the string to a char array.

char data type car variable holds a single character not the same as string of one character stores a number that corresponds to a character, but will be converted back ascii codes, a goes to 65 to assign characters to variables we use single quotes fin.get(c); gets a single character from the file and moves file pointer to the next charact er encryption example 'a' <-> 32 'c' <-> 34 'c' > 3 discussion 3/7/13 file i/o stream objects cin cout fin fout #include<fstream> if stream fin; of stream fout; #include<iostream> cin.fail cout fin.open("----"); fout.open("-----", iso::app); if doesnt exist, it creates the file string des; getline(cin.des) des.c_str(); fin >> takes in data from file fout << writes data into file fin.get(c); we get the character in from the file and assigns it to c charc void fill_from_file (int a[][], int m, int n, &fin) //need to pass fin and fout to this function fin.close() fout.close() int main{ string des = " " ifstream fin; fin.open(des.c_str()); string name, grade; int credit while(fin>>name>>credit>>grade) { st = conversion(grade)*credit; s_credit +=credit; } s/s_credit;

//calculus 4 A

int n, m; cin >>m >>n; ifstream fin; fin.open(des1, _str()); void fill_from_file(double a[][10], int m, int n, ifstream &fin)

{for(int i=0, i<m; i++) for(int j=0, j<n, j++) {fin >> a[i][j]; fill_from_file(a, m, n, fin); fill_from_file(b, n, e, fin): void multiplication(double a[][10], double b[][10], int m, int n, int l, double &c[10][10]) mxl { doublec[10][10]; for(int i =; i<m; i++) for(int j=0, j<l; j++) for(int k =0, k<n; k++) c[i][j]+=a[i][k]*b[k][j]; string des2; fout.open(des2 c_str()); for(i=0; i<m; i++) {for(j=0; j<l,j++) fout<<setw(5)<<c[i][j]; fout<<"\n"; fin.open( ) fout.open( )

lecture 3/8/13 file io if we want the faile name to come from a variable, use .c_str() eof end of file if (letter is \n return letter pointers - a variable that stores the address of another variable cout <<&x gives you the address declaring a pointer type*name; int *p; declares an integer pointer but is unintialized int a=2; p = &a //p now points to a p stores the address of a *p = 5 //*p is the value of the object at point p *p dereferencing p pointer fun examples p can only point to int variable declare two pointers, need two stars they need to point to stuff first p1=p2 //p1 now points at p2

heap vs stack memory heap stays alive until programmer deallocates it pointers create objects with longer life span delete p; //p is not deleted, just the memory 3/11/13 lecture pointers pointers are a variable that store smemory address *p derefences the pointer *p accesses that address and you can assign it stuff cout *p1 and cout a will give 7 no stars means addresses heap memory and stack memory new int accesses heap memory and gives it some free space for the pointer only p can access the new memory product * p p = new Product; if you use new, the product will now have a longer life, until you delete it in the heap memory delete p deletes the memory at p p = NULL if it is not pointing ot anything useful pointers make things efficient putting classes to vectors have the boss be a pointer (*p).get_name() use parenthesis to hold pointer have the department store a pointer to a person class rather than a whole person class classes in vectors instead of moving classes, move pointers use person * instead of person linked list POINTERS DISCUSSION 3/12/13 syntax to declare pointer int *p; but *p, when used, refers to the value of the variable (dereferencing) never use a dangling pointer always assign p a meaningful address first int *p; int a=5; p = &a; *p=4; int *p = new Point(x, y); class Point; first creates a space, then have the constructor for the class new delete p; p = null; //deletes the stuff inside the address <cstdlib> //p points to nothing

int *p; p = &a; //but a must be an integer example void fun(int*p, int *&q) { *p = 2; q = p; int c = 7; p = &c; return; } int main() { int x=5, y = 10; int *a = &x, *b = &y; fun(a,b) cout << *a << *b; return 0; } x 5 A y 10 B

pointer a is A, b is B void(local copy of p in the function int*p=a; *p = 2 now means the stuff inside p changes to 2, and the input was a so now the stuff in a is turned to 2 q = p now means q is given a as the address p = &c now means p is given address of c now *a and *b is 2 and now b changes address so now points to x 22 class node { public: private: int data; node *next; } node::node() { data = 0; next = null; } node::node(int m) { data = m; next = null; } node *head, *index, *temp;

head = new node; while(cin>>m) { new node(m); *p.____(); get_next(); //gets pointer void insert(int *p, int m, int i) //insert an int m in the ith position of the chain starting with p { int j=0; while(p > get_next()!=NULL && j,i) { p = p -> get_next(); i++; } lecture 3/13/13 use a member pointer to a boss object declare objects in the heap memory arrow notation to get print arrays name is pointer to beginning of array if you have pointer p = numbers then cout *p and numbers[0] then they will both be 1 now p++ makes sense with arrays the [] acts as dereferencing operator for array we can also use p[3] = 0 array is const, so thats why you cant set arrays equal to each other 10203405 example 1 2 3 20 30 3/14/13 discussion new Person(name); Person(string name); input names of best friends for each person, read in the name of the best friend for loop to visit and match the names visit the vector to match the names set_best_friend class node { int data node *next node * before } void insert(node *head, int number, int position) { int j = 0; while(head->get_next()! = NULL && j<post in) { head = head - > getnext(); j++;

} int *q = new(number); q.setnext(head->getnext void fun(int *&p){ *(p+3) = 40; p++ *p = 20 } main() int MyArray[5] = {1, 2, 3, 4, 5}; int *p = MyArray; fun(p); *p = 10; 1 10 3 40 5 need to know syntax string avoid errors variables data types i/o math<> libraries strings all operations using classes graphics if loops functions pass by value pass by reference, scope random numbers - seed, generate vector const for accessors member functions vectors arrays and pointers file i/o fstream ifstream fin ofstream fout fin.open() overloading 3/15/13 lecture array name as pointer numbers is same as &numbers[0] arrays name is pointer to the first element p++ will move the pointer along the array *(numbers+3) = 0 is also numbers[3]=0 pointers changing values declaring pointers return a pointer to a class swap random numbers class declaration int *p = x+2; //would point to ? 100 2 64

FINAL REVIEW string int length(): returns the number of characters in your string string substr(int start, int #ofcharacters to substring) //start at index, get # of characters to return string insert(int start, string to insert) a = alex b = wang, a insert(1,b) awanglex string a = "alex", a[2] = e string clear; cin >> x getline(cin, x) //grabs input delimited by space if you use cin and then use getline, then you must use string clear, because get line is delimited by newline and cin is delimited by space GRAPHICS ccc_win h Points Circles Lines Messages message (point p, string s) prints s at p for moving cwin.clear() animation Point p for cwin << o; cwin.clear() pmove VECTORS vector <datatype> name vecotr <datatype> name(size) vector <int> a; a[0] = 2; //incorrect a.pushback(2); b.push_back(1); a.pop_back(); size FILE I/O <fstream> <ifstream> <ofstream> ifstream fin; open(cstring, filename.c_str()) fin.close(); fin >> x delimited by space getline(fin,x) string baggins double 1120 alex 100

strin s; double d; fin >>S; fin >>d; pass by reference for fin and fout so they remember where to print while (fin >>x) read until bad input pointers datatype* name; int* x; int a = 5; x = &a *x = 10 *&a = 10 &*a = error *&x = the address of a void settoten(intxa) intx = 10 *a = x void settoten(int* &a) int x=10 a = &a; void settoten(int*&a) int* x = newint; *x = 10 a=x; //need to delete pa int main int * pa; settoten(a\pa) cout << *pa; delete pa pa = NULL; return 0; int main() Point *p getNewPoint(pp); cout << (*p) get.x() cout << pp -> get_y() delete pp; return 0 -> calls the function through pointer pp -> get_y(); delete pp; pp=NULL; function to return pointer

int* newInt() { int* a = newint; return a; } dereference array (*arr) // 1 *(arr+1) //2 (*arr)+1 //1+1 = 2 arr[0]; //1 (*arr) delete arr; arr = NULL int* arr = new int[r]