44
CS246: Midterm Review June 25, 2013

CS246: Midterm Review

Embed Size (px)

DESCRIPTION

CS246: Midterm Review. June 25, 2013. Agenda. Shell C++ Questions. Globbing. * matches 0 or more characters ? Matches 1 character {…} matches any item in the set […] matches 1 character in the set [!...] matches 1 character not in the set Use – to create ranges. Globbing examples. - PowerPoint PPT Presentation

Citation preview

Page 1: CS246: Midterm Review

CS246: Midterm Review

June 25, 2013

Page 2: CS246: Midterm Review

Agenda

• Shell

• C++

• Questions

Page 3: CS246: Midterm Review

Globbing

• * matches 0 or more characters

• ? Matches 1 character

• {…} matches any item in the set

• […] matches 1 character in the set

• [!...] matches 1 character not in the set

• Use – to create ranges

Page 4: CS246: Midterm Review

Globbing examples

• All non-hidden files in the current directory with at least 2 character prefix and ending in .h, .C, .cc, .cpp

• ??*.{h,C,cc,cpp}• All non-hidden files in the current directory that start and

end with a letter.• [a-zA-Z]*[a-zA-Z] • All files in the directories A1,A2,A3,A4 starting with cs.• A[1-4]/cs*

Page 5: CS246: Midterm Review

Regular Expressions

• ^ - Beginning of the line• $ - End of the line• . - Any single character• […] - any character in the set• [^…] - any character not in the set• a|b - matches a or b• * - 0 or more of the previous item• + - 1 or more of the previous item• {m,n} – m to n of the previous item• You can omit the m or the n. What does that do?

Page 6: CS246: Midterm Review

RE Examples

• Give a RE for lines starting with abc and ending with xyz• “^abc.*xyz$” - why quotes?• Give a RE for lines matching foo at least 5 times in a row

OR bar at least once in a row• “(foo){5,}|(bar)+”• Give a RE for lines consisting only of characters not in

the set {a,b,c,t,j,4,8,w}• “^[^abctj48w]+$”

Page 7: CS246: Midterm Review

Shell commands

• Know basic commands: grep, wc, man, chmod, cat, ls, etc…

• Know common options and what they do: e.g. ls –l, grep –E, wc -l.

Page 8: CS246: Midterm Review

Shell commands – ls

• Prints the contents of the specified directory• -l : prints the contents in Long form• -a : prints All files• Reading long form results:-rw-r--r-- 1 Kevin None 16 Sep 30 19:39 suitedrwxr-xr-x 1 Kevin None 0 Oct 22 11:59 test-rw-r--r-- 1 Kevin None 86 Sep 23 14:53 test.txt-rw-r--r-- 1 Kevin None 86 Sep 25 16:26 test1.txt

Page 9: CS246: Midterm Review

I/O redirection

• 0 – stdin, 1 – stdout, 2 – stderr.• ./script 1> file: redirects stdout to a file• ./script 1>&2 : redirects stdout to stderr• ./script >& file : redirects stdout and stderr to a file• ./script < file : redirects the contents of file to stdin.

Page 10: CS246: Midterm Review

I/O redirection

• Example:

• wc –l myfile

• 4 myfile

• wc –l < myfile

• 4

Page 11: CS246: Midterm Review

Conditional Tests

• Used in if statements, while loops, etc• [ ] are an alias for a command called test, which tests if

the following expr is true (and so returns 0) or false (and so returns 1)

• ! has highest priority• \( expr \) has next highest (used to group together expr's)• expr1 -a expr2 has next highest• expr1 -o expr2 has lowest priority

Page 12: CS246: Midterm Review

Conditional Tests

• String tests: =, !=

• Integer tests: -eq, -ne, -ge, -gt, -le, -lt

• File tests : -d, -f, -e, -r, -w, -x

• Examples:

• [ \( -f file -a -x file \) -o -w file ]

• [ “cat” != “dog” ]

• [ 5 -lt 6 -a 6 -ge 6 ]

Page 13: CS246: Midterm Review

Conditional Tests

The exit code of a command can be used in place of [ ]

(test)if ! diff file1 file2 >& /dev/nullthen

echo “file1 and file2 are different”else

echo “file1 and file2 are the same”fi

Page 14: CS246: Midterm Review

Quoting

• Backslash (\) - escapes any character• > echo \.\[\!\.\]\*• .[!.]*• Backquote (`) - executes text as a command• > echo `wc -l text`• 4• Single quote (') – literally whatever is inside.• > echo '\.\[\!\.\]\*'• \.\[\!\.\]\*• Double quote (“) - recognizes escapes, backquotes, and• variables

Page 15: CS246: Midterm Review

Example#!/bin/bashusage(){echo “$0 file-name” 1>&2}count1=0 #number of words that are 'Hello'count2=0 #number of words that are not 'Hello'if [ $# -ne 1 ]; then

usage; exit 1fifor word in `cat $1`; do

if [ “$word” = “Hello” ]; thencount1=$((${count1}+1))

elsecount2=$((${count2}+1))

fidoneecho “Hello appeared $count1 times.”echo “Non-Hello words appeared $count2 times.”

Page 16: CS246: Midterm Review

C++

• Control structures you should have learned in cs136 are not reviewed

• Ifs, loops etc;

Page 17: CS246: Midterm Review

Strings

• To use, include the <string> library

• Encapsulated form of C-strings

• Individual characters are accessed with [ ]

• Useful methods: substr, length, + for concatenation, < for comparison.

Page 18: CS246: Midterm Review

C++ I/O Streamsint x,y;cin >> x;cin >> y;cout << x << “ and “ << y << endl;

If given 123,456 as input, output?

If given 123 456 as input, output?

The type of operand to >> dictates what’s expected on input.>> is overloaded for many different types such as ints, strings, doubles etc...

Page 19: CS246: Midterm Review

C++ I/O Streams

• Detect the end of file:• Stream member eof returns true if end of file is

reached• Stream member fail returns true if eof or invalid

literal is seen• Streams can be used as part of conditional tests

While (cin >> x) {…}

Page 20: CS246: Midterm Review

C++ filestreams

• Part of <fstream> library• ifstream in; // read from file, like cin• ofstream out; //output to file, like cout• Open and close filestreams

ifs.open(“infile” ); // could have done ifstream ifs(“infile” );

if(ifs.fail()) cerr << “ File did not open” << endl;... // Process file

ifs.close(); // Ensures no corruption of file data

Page 21: CS246: Midterm Review

Pointers and References

int x = 42;int *y = &x; // y points to xint &z = x; // z is a reference to x.

What is printed?cout << x == z << &x == y << &z == y << &z

== &x << endl;

Page 22: CS246: Midterm Review

Pointers and References

int v = 42;const int w = v;const int *x = &v;int * const y = &v;const int * const z = &v;Which lines cause an error?int *a = &v;int *b = &w;*x = 50;*y = 50;y = &w;

Page 23: CS246: Midterm Review

Pointers and References

How are pointers and references different?int x;int *y = &x;int &z = x;

z would almost appear to be a const pointer to x

In fact, the difference between a pointer (y) and a reference (z) is an extra implicit dereference

Page 24: CS246: Midterm Review

Pointers and References

That is, if we have:int x =4, y=2;int *p1 = &x, *p2 = &y;int &r1 = x, &r2 = y;Then it is the difference between

*p2 = (*p2+*p1) / (*p2 - *p1)and

r2 = (r2 + r1) / (r2 – r1)It depends on if you want the compiler to do the work foryou.

Page 25: CS246: Midterm Review

Pointers and References

Pass by value:• void foo ( int x);• void foo ( int *x);

Pass by reference:• void foo ( int &x);• void foo ( const int &x);

The difference between them is how parameters aretreated (copied or not) and not whether changes arepassed back

Page 26: CS246: Midterm Review

Overloading

• Occurs when a name has multiple meanings in the same context

• Most languages have some level of implicit overloading,

• e.g. operator+ for integers, floats and strings• Number and type of parameters are used to

select which same-named function to use• Return type is not considered

Page 27: CS246: Midterm Review

Overloading

• Parameter types with qualifiers: signed, const or reference with the same base type are not unique

void r(int i){…}void r(signed int i){…} // not uniquevoid r(const int i){…} // not uniquevoid r(int& i){…} // not uniqueint r(int i){…} // not unique

void r(unsigned int i){…}// uniquevoid r(int i, int j){…} // uniquevoid r(long int i){…} // unique

Page 28: CS246: Midterm Review

Operator Overloading

• Operators are just like functions except they are infix instead of prefix.

Think of

a+bas

+(a,b)where + is the function name.• Overload them like you would for functions.• When the operator is a member function, this is the

Left-hand side.

Page 29: CS246: Midterm Review

Stream Operator Overloading

• Two I/O operators to overload:• >> input operator, << output operatoristream& operator>> (istream& is, <type> var);ostream& operator<< (ostream& os, <type> var);

• Note that istream works for all kinds of input streams (cin, ifilestreams, istringstreams etc..)

• Always remember to return the same stream that you pass in (to allow for cascading)

myClass a,b,c;cin >> a >> b >> c;

Page 30: CS246: Midterm Review

Overloading

Can be thought of as:((cin >> a) >> b) >> c;

Where cin >> a calls the overloaded operator:istream& operator>> (istream& in, myClass x);

If you return the same stream that was passed in:(cin >> b) >> c;

Allows for cascading. Do similar things for other operators that can be cascaded like <<, + etc.

Page 31: CS246: Midterm Review

Dynamic Memory Management

• C++ provides dynamic memory allocation with new/delete

• C uses malloc/free – do not use these unless told to• Memory for dynamic allocation comes from the heap• If the heap is full, new generates an error• Storage must be deleted when not needed any moreint *p = new int;delete p;

Page 32: CS246: Midterm Review

Dynamic Memory Management

• C++ allows everything to be dynamically allocated or allocated on the stack

• Stack allocation eliminates explicit storage management and is more efficient than heap allocation

• Dynamic allocation in C++ should only be used when a variable's storage must outlive the block in which it is allocated

Page 33: CS246: Midterm Review

Dynamic Memory Management

• Arrays on the heap:• Multi-dimensional heap based arrays are tricky• Basic idea: extended the concept of a 1-D array.int *pArrs[10]; //partially stack basedint **pArrh=new int*[10];//completely heap based

for (int i=0; i<10; i++) {pArrs[i] = new int[10];pArrh[i] = new int[10];

}

Page 34: CS246: Midterm Review

Dynamic Memory Management

• New operator allocates memory, delete operator deallocates memory.

• New returns a pointer, delete accepts a pointer.int *j = new int(5);delete j;

Deleting arrays are trickyfor (int i=0; i<10; i++) {

delete[] pArrs[i];delete[] pArrh[i];

}delete [] pArrh;

Why do we not delete pArrs?

Page 35: CS246: Midterm Review

Structs and Classes

• A combination of data members and operations on the data together.

• Members has 2 basic types: public and private• Public members can be accessed from outside

the class• Private members cannot be accessed from

outside the class• Structs’ members are default public• Classes’ members are default private

Page 36: CS246: Midterm Review

Structs and Classes

struct ComplexNum {private:

…};class ComplexNum {

…};

Are the same.

Page 37: CS246: Midterm Review

class ComplexNum {int real,im;public:

ComplexNum();ComplexNum(int r, int i); //overload//could be an operatorvoid add(const ComplexNum&);int getReal(){ return real;}int getIm() { return im;}

};

Classes

Page 38: CS246: Midterm Review

ComplexNum add(const complexNum& other) {return other;

}void ComplexNum::add(const ComplexNum& other) {

real += other.getReal();im += other.getIm();

}//Assume other functions are defined in the obvious way

int main() {ComplexNum a1(5,3);cout << a1.real << endl; //not allowed why?cout << a1.getReal() << endl;add(a1); //which add is called?a1.add(a1); //which add is called?

}

Page 39: CS246: Midterm Review

Constructors• Has no return type, and same name as the class• Used to initialize the members of the class• Initialize variables in a way to preserve an invariant that

your class may have.• Ex: A rational number class should always be in lowest

forms.• Suppose we want our complex number class to have

only positive reals at all times.

ComplexNum::ComplexNum(int r, int i) :real(r), im(i) {

if ( real < 0 ) real *= -1; //make real positive}

Page 40: CS246: Midterm Review

Destructors• Has no return type, name of class with ~ prefix• Used to “destroy” the object• Mainly needed to deallocate any dynamically allocated

memory of the classclass Ptr {

int* randomptr;public:

Ptr() { randomptr = new int(20);}~Ptr();

};Ptr::~Ptr() {

if (randomptr != NULL) delete randomptr;}

Page 41: CS246: Midterm Review

Assignment Operator

• If you have to overload any one of the following you probably have to overload all three– Copy Constructor– Destructor– Assignment Operator

Page 42: CS246: Midterm Review

Assignment Operator (cont.)class Pointer {

int *ptr;Pointer(const Pointer &p) {

ptr = new int;*(ptr) = *(p.ptr);

}~Pointer() {

delete ptr;}Pointer &operator=(const Pointer &p) {

*(ptr) = *(p.ptr);return *(this);

}};

Page 43: CS246: Midterm Review

Singleton Pattern

• Design Pattern: Technique for solving common situations.

• Example: Singleton Pattern– We want to ensure that only one instance of a class gets

created.

• How? Use static• Static variables are associated with an entire class• Keep a static pointer to the instance• Do not give the user access to constructors, and only let

them use your custom static getInstance() methods.

Page 44: CS246: Midterm Review

Questions?