CS246: Midterm Review

Post on 01-Jan-2016

40 views 2 download

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

Transcript of CS246: Midterm Review

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

• 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*

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?

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]+$”

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.

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

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.

I/O redirection

• Example:

• wc –l myfile

• 4 myfile

• wc –l < myfile

• 4

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

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 ]

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

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

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.”

C++

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

• Ifs, loops etc;

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.

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...

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) {…}

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

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;

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;

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

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.

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

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

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

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.

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;

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.

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;

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

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];

}

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?

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

Structs and Classes

struct ComplexNum {private:

…};class ComplexNum {

…};

Are the same.

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

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?

}

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}

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;}

Assignment Operator

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

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);

}};

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.

Questions?