101
09.12.2012 1 LECTURE 11 LECTURE 11 Binary files Binary files Binary files are not text files, because they are not coded according to ASCII or any other coding standard. In binary files, the input and output of data with format like the provided by the operators << and >> or functions such as getline do not make much sense. File streams include two member functions specially designed for sequential input and output of data: write and read. write is a member function of ostream, also inherited by ofstream. read is a member function of istream and it is inherited by ifstream. Objects of class fstream have both. Their prototypes are: write ( char * buffer, streamsize size ); read ( char * buffer, streamsize size ); The buffer parameter is the address of a memory block where read data are stored or where the data to be written is taken from. The size parameter is an integer value that specifies the number of characters to be read/written from/to the buffer. Buffers & synchronization Buffers & synchronization When the buffer is emptied, all data it contains is written to the physical media (if it is an output stream) or simply erased (if it is an input stream). This process is called synchronization and it takes place under any of the following circumstances: When the file is closed. When the buffer is full. Explicitly with these manipulators: flush, endl. Explicitly with function sync(). Serialization Serialization Serialization is the process of converting a data structure or object into a format that can be stored (for example, in a file or memory buffer). Deserialization is the process of converting serial data into data structures or objects. Random access Random access Random access (sometimes called direct access) is the ability to access an arbitrary element of a sequence in equal time. The opposite is sequential access, where a remote element takes longer time to access. Random access files Random access files

Complete Computing Slides

  • Upload
    humza

  • View
    70

  • Download
    1

Embed Size (px)

DESCRIPTION

Orientation to Computing (Undergraduate Level)

Citation preview

Page 1: Complete Computing Slides

09.12.2012

1

LECTURE 11LECTURE 11

Binary filesBinary files Binary files are not text files, because they are not coded

according to ASCII or any other coding standard. In binary files, the input and output of data with format like the

provided by the operators << and >> or functions such as getline do not make much sense.

File streams include two member functions specially designed for sequential input and output of data: write and read. ◦ write is a member function of ostream, also inherited by ofstream. ◦ read is a member function of istream and it is inherited by ifstream.

Objects of class fstream have both. Their prototypes are:◦ write ( char * buffer, streamsize size );◦ read ( char * buffer, streamsize size );

The buffer parameter is the address of a memory block where read data are stored or where the data to be written is taken from.

The size parameter is an integer value that specifies the number of characters to be read/written from/to the buffer.

Buffers & synchronizationBuffers & synchronization When the buffer is emptied, all data it

contains is written to the physical media (if it is an output stream) or simply erased (if it is an input stream).

This process is called synchronizationand it takes place under any of the following circumstances:◦ When the file is closed.◦ When the buffer is full.◦ Explicitly with these manipulators: flush,

endl.◦ Explicitly with function sync().

SerializationSerialization Serialization is the process of

converting a data structure or object into a format that can be stored (for example, in a file or memory buffer).

Deserialization is the process of converting serial data into data structures or objects.

Random accessRandom access Random access (sometimes called

direct access) is the ability to access an arbitrary element of a sequence in equal time.

The opposite is sequential access, where a remote element takes longer time to access.

Random access filesRandom access files

Page 2: Complete Computing Slides

09.12.2012

2

Overloading operatorsOverloading operators One of the important features of C++ is that

special meanings can be given to operators, when they are used with user-defined classes. This is called operator overloading.

C++ operator overloads can be implemented by providing special member-functions on classes that follow a particular naming convention.

For example, to overload the + operator for your class, you would provide a member-function named operator+ on your class.

Overloading operatorsOverloading operators The following set of operators is

commonly overloaded for user-defined classes: ◦ = (assignment operator) ◦ + - * (binary arithmetic operators) ◦ += -= *= (compound assignment operators) ◦ == != (comparison operators)

Multiple InheritanceMultiple Inheritance Multiple inheritance allows a class to

take on functionality from multiple other classes.

Ambiguities arise in multiple inheritance are referred to as the Diamond problem. ◦ This can often be solved by virtual

inheritance.

The diamond problemThe diamond problem The diamond

problem is an ambiguity that arises when two classes Band C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A(and does not overridethe method), and Band C have overridden that method differently, then from which class does it inherit: B, or C?

Page 3: Complete Computing Slides

17.12.2012

1

LECTURE 12

Polymorphism

Polymorphism is a feature that allows values of different data types to be handled using a uniform interface.

The concept of parametric polymorphism applies to both data types and functions. ◦ A function that can evaluate to or be applied

to values of different types is known as a polymorphic function.

◦ A data type that can appear to be of a generalized type (e.g., a list with elements of arbitrary type) is designated polymorphic data type like the generalized type from which such specializations are made.

Polymorphism

Next there is as an

example for class

(data type)

polymorphism

◦ Here, Employee is

the base class that

inherits to all the

other three classes.

Templates

Templates are a feature of the C++ programming language that allow functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one. ◦ Templates are of great utility to

programmers in C++, especially when combined with multiple inheritance

We use the term recursion when a function or method calls itself.

Recursion is often used in computer science and programming when the solution to a problem depends on solutions to smaller instances of the same problem. ◦ Compare: Many mathematical axioms are based upon

recursive rules. For example, the formal definition of the natural numbers in set theory follows: 1 is a natural number, and each natural number has a successor, which is also a natural number. By this base case and recursive rule, one can generate the set of all natural numbers

Recursion (1) Recursion (2)

Factorial as an example for linear

recursion:

n = 4

Page 4: Complete Computing Slides

17.12.2012

2

Recursion (3)

Fibonacci numbers as an example for

cascaded recursion:

Recursion (3a)

Fibonacci numbers (n = 6)

Recursion (3b)

Euclidian algorithm (greatest common

denominator)

Recursion (4)

Primitive recursion

Recursion (5)

Basic examples for primitive recursion

Recursion (6)

Don‘t forget:

◦ Every recursive method must have

a start condition

an end condition

(This leads us directly to the problem of computability, which

is a topic that is extensively dealt with in theoretical computer

science. The computability of a problem is closely linked to

the existence of an algorithm to solve the problem.)

Page 5: Complete Computing Slides

17.12.2012

3

LECTURE 13

Recursion (7)

„Divide & Conquer“ principle as given

in two examples:

Towers of Hanoi ◦ Given three pegs, one with a set of N disks of increasing size,

determine the minimum (optimal) number of steps it takes to

move all the disks from their initial position to another peg without

placing a larger disk on top of a smaller one.

Function definition:

Recursion (7a)

Towers of Hanoi (cont‘d)

Recursion (7b)

Quicksort ◦ Quicksort first divides a large list (which might be

represented as an array) into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists.

◦ The algorithm is: Pick an element, called a pivot, from the list.

Re-order the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.

Recursively sort the sub-list of lesser elements and the sub-list of greater elements.

◦ The base case of the recursion are lists of size zero or one, which never need to be sorted.

Recursion (7c)

Quicksort

Recursion (7d)

Quicksort (pseudocode)

Page 6: Complete Computing Slides

17.12.2012

4

Recursion (7e) - Quicksort Tail Recursion (1)

Disadvantages of recursions ◦ Recursive procedures call themselves to work

towards a solution to a problem. In simple

implementations this balloons the stack as the

nesting gets deeper and deeper, reaches the

solution, then returns through all of the stack

frames. This waste is a common complaint about

recursive programming in general.

Solution: tail recursion

Tail Recursion (2)

A function call is said to be tail recursive if there is nothing to do after the function returns except return its value.

Since the current recursive instance is done executing at that point, saving its stack frame is a waste. Specifically, creating a new stack frame on top of the current, finished, frame is a waste.

A compiler is said to implement tail recursion if it recognizes this case and replaces the caller in place with the program that calls, so that instead of nesting the stack deeper, the current stack frame is reused.

This is equivalent in effect to a GoTo, and lets a programmer write recursive definitions without worrying about space inefficiency during execution.

Tail recursion is then as efficient as iteration normally is.

Tail Recursion (3)

Sometimes it is necessary to optimize tail

recursion:

◦ If the last thing a routine does before it returns is

call another routine, rather than doing a jump-

and-add-stack-frame immediately followed by

a pop-stack-frame-and-return-to-caller,

it should be safe to simply jump to the start of

the second routine, letting it re-use the first

routine's stack frame.

◦ Most compilers will generate suboptimal code.

Sieve of Erathostenes

Sieve of Eratosthenes is a simple algorithm to find prime numbers, although today there exist better algorithms.

The algorithm requires a bit array isComposite to store n - 1 numbers: isComposite[2 .. n]. Initially the array contains zeros in all cells. During the algorithm's work, numbers, which can be represented as k * p, where k ≥ 2, p is prime, are marked as composite numbers by writing 1 in a corresponding cell. The algorithm consists of two nested loops: outer, seeking for unmarked numbers (primes), and inner, marking primes' multiples as composites.

Sieve of Erathostenes

For all numbers m: 2 .. n, if m is

unmarked:

◦ add m to primes list;

◦ mark all its multiples, equal to or lesser

than n (k * m ≤ n, k ≥ 2);

otherwise, if m is marked, then it is a

composite number.

Page 7: Complete Computing Slides

17.12.2012

5

Sieve of Erathostenes (improvement)

For all numbers m: 2 .. √n, if m is

unmarked:

◦ add m to primes list;

◦ mark all its multiples, starting from square,

lesser than or equal to n (k * m ≤ n, k ≥ m);

otherwise, if m is marked, then it is a

composite number;

check all numbers in range √n .. n. All

numbers found unmarked are primes,

add them to list.

Page 8: Complete Computing Slides

1

// Polymorphism

#include <iostream>

using namespace std;

class Employee // base class

{

protected:

double salary;

public:

Employee(double value)

{

salary = value;

}

virtual ~Employee()

{

cout << "base class destructor" << endl;

}

virtual void promoted()

{

salary += 1000;

}

virtual double getSalary()

{

return salary;

}

};

class Trainee : public Employee

{

public:

Trainee(double value):Employee(value) {}

virtual void promoted()

{

salary += 200;

}

};

class Clerk : public Employee

{

public:

Clerk(double value) : Employee(value) {}

};

class Manager : public Employee

{

public:

Manager(double value):Employee(value) {}

virtual void promoted()

{

salary *= 1.2;

}

};

int main()

{

// Implicitly making use of polymorphism

/*

Trainee *john = new Trainee(1000);

Clerk *steven = new Clerk(4200);

Clerk *maggie = new Clerk(5700);

Manager *jill = new Manager(8500);

*/

// Explictly making use of polymorphism

// initialize polymorphic inherited objects

Page 9: Complete Computing Slides

2

// define object variable of the kind "Employee"

Employee *john;

Employee *steven;

Employee *maggie;

Employee *jill;

// assign address space to object variable of different kinds

john = new Trainee(1000);

steven = new Clerk(4200);

maggie = new Clerk(5700);

jill = new Manager(8500);

john->promoted();

cout << "John gets " << john->getSalary() << endl;

steven->promoted();

cout << "Steven gets " << steven->getSalary() << endl;

maggie->promoted();

cout << "Maggie gets " << maggie->getSalary() << endl;

jill->promoted();

cout << "Jill gets " << jill->getSalary() << endl;

delete john;

delete steven;

delete maggie;

delete jill;

system("PAUSE");

return 0;

}

-------------------------------------------------------------------------------

// class template

#include <iostream>

#include <string>

using namespace std;

template <class T>

class CPair

{

private:

T value1, value2;

public:

CPair (T first, T second);

T getmax ();

void swap();

T getvalues();

};

template <class T>

CPair<T>::CPair(T first, T second)

{

value1 = first; value2 = second;

}

template <class T>

T CPair<T>::getmax()

{

return value1>value2 ? value1 : value2;

}

template <class T>

void CPair<T>::swap()

{

T temp;

temp = value1; value1 = value2;

Page 10: Complete Computing Slides

3

value2 = temp;

}

template <class T>

T CPair<T>::getvalues()

{

cout << "("<<value1<<","<<value2<<")"<<endl;

}

//------------------------------------------

int main ()

{

CPair <int> myobject1 (100, 75);

CPair <char> myobject2('w','z');

CPair <string> myobject3("Ulrich","Brosig"); // string is a class

cout << myobject1.getmax() << endl;

cout << myobject2.getmax() << endl;

cout << myobject3.getmax() << endl;

myobject2.swap();

myobject3.swap();

myobject2.getvalues();

myobject3.getvalues();

system("pause");

return 0;

}

------------------------------------------------------------------

Page 11: Complete Computing Slides

14.01.2013

1

LECTURE 14

Namespaces

Namespaces allow us to group a set of global classes, objects and/or functions under a name.

Here identifier is any valid identifier and namespace-body is the set of classes, objects and functions that are included within the namespace

namespace identifier

{

namespace-body

}

Namespaces

In the example opposite, a and b are normal variables integrated within the general namespace. In order to access to these variables from outside the namespace we have to use the scope operator :: .

For example, to access the variables given opposite we would have to put: ◦ general::a

◦ general::b

namespace general

{

int a, b;

}

‘using namespace’

The using directive followed by namespace serves to associate the present nesting level with a certain namespace so that the objects and functions of that namespace can be accessible directly as if they were defined in the global scope. Its utilization follows the prototype: ◦ using namespace identifier;

One of the best examples that we can find about namespaces is the standard C++ library itself. ◦ According to ANSI C++ standard, the definition of all

the classes, objects and functions of the standard C++ library are defined within namespace std.

Typecasting

For basic types

typecasting can be

done this way:

This way of writing

can also be applied

to pointers and

classes

int i;

double d;

i = (int) d;

Typecasting

In order to control conversions between

classes, ANSI-C++ standard has defined

four casting operators, all of which have

the same format.

reinterpret_cast <new_type> (expression)

dynamic_cast <new_type> (expression)

static_cast <new_type> (expression)

const_cast <new_type> (expression)

Page 12: Complete Computing Slides

14.01.2013

2

Typecasting

reinterpret_cast casts a pointer to any other type of pointer. It also allows casting from pointer to an integer type and vice versa.

static_cast allows to perform any casting that can be implicitly performed as well as also the inverse cast (even if this is not allowed implicitly).

dynamic_cast is exclusively used with pointers and references to objects. It allows any type-casting that can be implicitly performed as well as the inverse one when used with polymorphic classes. ◦ However, unlike static_cast, dynamic_cast checks if

the operation is valid.

Typecasting

const_cast manipulates the const

attribute of the passed object either to

be set or removed.

typeid is an operator that allows to

check the type of an expression.

LECTURE 15

Keyword static When modifying a variable, the static keyword specifies that the variable has

static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to 0 unless another value is specified. When modifying a variable or function at file scope, the static keyword specifies that the variable or function has internal linkage (its name is not visible from outside the file in which it is declared).

A variable declared static in a function retains its state between calls to that function.

When modifying a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. When modifying a member function in a class declaration, the static keyword specifies that the function accesses only static members.

Static data members of classes must be initialized at file scope.

In recursive code, a static object or variable is guaranteed to have the same state in different instances of a block of code.

Objects and variables defined outside all blocks have static lifetime and external linkage by default. A global object or variable that is explicitly declared as static has internal linkage.

Curried Functions (Currying)

Curried functions are functions of more than one arguments that take “one argument at a time”, instead of taking all arguments together. ◦ In general, for any function f of n

arguments from domains D1 to Dn that returns a result in domain Dr:

◦ f: D1 x D2 x ... x Dn -> Dr

◦ there is a curried equivalent:

◦ curry f: D1 -> (D2 -> ... ->(Dn ->Dr))

Currying (2)

In other words, curry f is a function

that takes a first argument a1 and

returns a function, which in turn

takes an argument and returns

another function, which continues the

same process until all arguments are

present, at which point the original

function f is evaluated to yield a

result.

Page 13: Complete Computing Slides

14.01.2013

3

Currying (3)

Code example: ◦ f(x,y) = y / x

◦ then the function g

◦ g x = \y -> f(x,y)

◦ is a curried version of f. In particular,

◦ g 2 = \y -> f(2,y)

◦ is the curried equivalent of the example above.

◦ Do not confuse this with partial functions, which were mentioned earlier.

STL – Standard Template Library

Offers a big choice of algorithms Basically uses the iterator interface Most of them must be included by

include <algorithm> ◦ std::copy, std::fill, std::find,

std::binary_search,

◦ std::sort, std::max_element, std::replace_if,

◦ std::transform, std::for_each, ...

Some are inside header std::<numeric> ◦ std::accumulate, std::inner_product,

std::partial_sum, ...

Page 14: Complete Computing Slides

1

/*

Problem FIND_IN_SORTED_ARRAY / Binary Search

Input: an array arr sorted in increasing order, an integer n

Output: index of n in arr, -1 if absent

*/

#include <cstdlib>

#include <iostream>

using namespace std;

int BinarySearch(int arr[], int n, int low, int high)

{

if (high < low)

{

if (arr[low] == n)

return low;

else

return -1;

}

else

{

if (arr[(low + high) / 2] < n)

return BinarySearch(arr, n, low, (low + high) / 2);

else if (arr[(low + high) / 2] > n)

return BinarySearch(arr, n, ((low + high) / 2) + 1, high);

else

return (low + high) / 2;

}

}

int main()

{

int array[] = {1,3,4,9,10,100,123,145,200};

int search_for = 10;

cout << BinarySearch(array,search_for,0,8) << endl;

system("PAUSE");

return EXIT_SUCCESS;

}

---------------------------------------------------------------------------------

// Basic Inline Assembly

/*

** GCC Inline Assembly Syntax

**

** Register Naming: Register names are prefixed with %, so that registers

are %eax, %cl etc, instead of just eax, cl.

Ordering of operands: Unlike Intel convention (first operand is

destination), the order of operands is source(s) first, and

destination last. For example, Intel syntax "mov eax, edx" will

look like "mov %edx, %eax" in AT&T assembly.

Operand Size: In AT&T syntax, the size of memory operands is

determined from the last character of the op-code name. The suffix

is b for (8-bit) byte, w for (16-bit) word, and l for (32-bit) long.

For example, the correct syntax for the above instruction would have

been "movl %edx, %eax".

Immediate Operand: Immediate operands are marked with a $ prefix, as

in "addl $5, %eax", which means add immediate long value 5

to register %eax).

Memory Operands: Missing operand prefix indicates it is a

memory-address; hence "movl $bar, %ebx" puts the address of variable

bar into register %ebx, but "movl bar, %ebx" puts the contents of

Page 15: Complete Computing Slides

2

variable bar into register %ebx.

Indexing: Indexing or indirection is done by enclosing the index

register or indirection memory cell address in parentheses. For

example, "movl 8(%ebp), %eax" (moves the contents at offset 8 from

the cell pointed to by %ebp into register %eax).

** The register constraints are as follows :

+---+--------------------+

| r | Register(s) |

+---+--------------------+

| a | %eax, %ax, %al | accumulator

| b | %ebx, %bx, %bl | base

| c | %ecx, %cx, %cl | counter

| d | %edx, %dx, %dl | data

| S | %esi, %si | index

| D | %edi, %di | index

+---+--------------------+

*/

#include <iostream>

using namespace std;

void simpleOperations()

{

/* Add 10 and 20 and store result into register %eax */

asm ( "movl $10, %eax;"

"movl $20, %ebx;"

"addl %ebx, %eax;"

);

/* Subtract 20 from 10 and store result into register %eax */

asm ( "movl $10, %eax;"

"movl $20, %ebx;"

"subl %ebx, %eax;"

);

/* Multiply 10 and 20 and store result into register %eax */

asm ( "movl $10, %eax;"

"movl $20, %ebx;"

"imull %ebx, %eax;"

);

}

int main()

{

/*

** In this example, the variable "val" is kept in a register,

** the value in register eax is copied onto that register, and

** the value of "val" is updated into the memory from this register.

** When the "r" constraint is specified, gcc may keep the variable in

** any of the available General Purpose Registers. We can also specify

** the register names directly by using specific register constraints.

*/

int no = 100, val ; // no initial value for val !!

asm ("movl %1, %%ebx;"

"movl %%ebx, %0;"

: "=r" ( val ) /* output */

: "r" ( no ) /* input */

: "%ebx" /* clobbered register */

);

/*

** Output operand constraint should have a constraint

** modifier "=" to specify the output operand in write-only mode.

Page 16: Complete Computing Slides

3

** There are two %’s prefixed to the register name, which

** helps GCC to distinguish between the operands and registers.

** Operands have a single % as prefix.

** The clobbered register %ebx after the third colon informs the

** GCC that the value of %ebx is to be modified inside "asm", so

** GCC won't use this register to store any other value.

*/

cout << val << endl;

//----------------------------------------------

/*

** Here "add" is the output operand referred to by register eax.

** And arg1 and arg2 are input operands referred to by

** registers eax and ebx respectively.

*/

int arg1=5, arg2=7, add ;

asm ( "addl %%ebx, %%eax;"

: "=a" (add) // output

: "a" (arg1), "b" (arg2) // input

);

cout << add << endl;

system("PAUSE");

return EXIT_SUCCESS;

}

========================================================================

// Inline assembly

/*

+---+--------------------+

| r | Register(s) |

+---+--------------------+

| a | %eax, %ax, %al |

| b | %ebx, %bx, %bl |

| c | %ecx, %cx, %cl |

| d | %edx, %dx, %dl |

| S | %esi, %si |

| D | %edi, %di |

+---+--------------------+

*/

#include <stdio.h> // necessary for inline assembly

#include <iostream>

int gcd( int a, int b ) {

int result ;

/* Compute Greatest Common Divisor using Euclid's Algorithm */

asm volatile (

"movl %1, %%eax;"

"movl %2, %%ebx;"

"CONTD: cmpl $0, %%ebx;"

"je DONE;"

"xorl %%edx, %%edx;"

"idivl %%ebx;"

"movl %%ebx, %%eax;"

"movl %%edx, %%ebx;"

"jmp CONTD;"

"DONE: movl %%eax, %0;" : "=g" (result) : "g" (a), "g" (b)

);

return result ;

Page 17: Complete Computing Slides

4

}

int main() {

int arg1, arg2, add, sub, mul, quo, rem ;

printf( "Enter two integer numbers : " );

scanf( "%d%d", &arg1, &arg2 );

/* Perform Addition, Subtraction, Multiplication & Division */

asm ( "addl %%ebx, %%eax;" : "=a" (add) : "a" (arg1) , "b" (arg2) );

asm ( "subl %%ebx, %%eax;" : "=a" (sub) : "a" (arg1) , "b" (arg2) );

asm ( "imull %%ebx, %%eax;" : "=a" (mul) : "a" (arg1) , "b" (arg2) );

asm ( "movl $0x0, %%edx;"

"movl %2, %%eax;"

"movl %3, %%ebx;"

"idivl %%ebx;" : "=a" (quo), "=d" (rem) : "g" (arg1), "g" (arg2));

printf( "%d + %d = %d\n", arg1, arg2, add );

printf( "%d - %d = %d\n", arg1, arg2, sub );

printf( "%d * %d = %d\n", arg1, arg2, mul );

printf( "%d / %d = %d\n", arg1, arg2, quo );

printf( "%d %% %d = %d\n", arg1, arg2, rem );

printf("-------------------------\n");

//----------------------------------------------

int first, second ;

printf( "Enter two integers : " ) ;

scanf( "%d%d", &first, &second );

printf( "GCD of %d & %d is %d\n", first, second, gcd(first, second) ) ;

system("pause");

return 0 ;

}

==================================================================================

/* The meaning of 'static'

You may use a static variable in order to preserve information

about the last value a function returned.

*/

#include <iostream>

using namespace std;

int main()

{

cout << "1st loop:" << endl;

for(int x=0; x<5; x++)

{

for(int y=0; y<5; y++)

{

int number_of_times = 0;

number_of_times++;

if(y==4) cout << number_of_times << endl; // 1, 1, 1, 1, 1

}

}

cout << "2nd loop:" << endl;

for(int x=0; x<5; x++)

{

for(int y=0; y<5; y++)

{

static int number_of_times = 0;

number_of_times++;

if(y==4) cout << number_of_times << endl; // 5, 10, 15, 20, 25

}

Page 18: Complete Computing Slides

5

}

system("PAUSE");

return EXIT_SUCCESS;

}

=========================================================================

// checked vector

#include<cassert>

#include<vector>

#include<string>

#include <iostream>

using namespace std;

namespace brosig_stl {

template<class T>

class checkedVector : public std::vector<T> { // erben

public:

// inherited data types

typedef typename checkedVector::size_type size_type;

typedef typename checkedVector::iterator iterator;

typedef typename checkedVector::difference_type difference_type;

typedef typename checkedVector::reference reference;

typedef typename checkedVector::const_reference const_reference;

checkedVector()

{ }

checkedVector(size_type n, const T& value = T())

: std::vector<T>(n, value)

{ }

checkedVector(iterator i, iterator j)

: std::vector<T>(i, j)

{ }

reference operator[](difference_type index)

{

//assert(index >=0 && index < static_cast<difference_type>(size()));

assert(index >= 0 && index < 4);

return std::vector<T>::operator[](index);

}

const_reference operator[](difference_type index) const

{

//assert(index >=0 && index < static_cast<difference_type>(size()));

assert(index >= 0 && index < 4);

return std::vector<T>::operator[](index);

}

};

}

int main()

{

// a string vector containing 4 elements

const int count = 4;

brosig_stl::checkedVector<std::string> stringVec(count);

stringVec[0] = "one";

stringVec[1] = "two";

stringVec[2] = "three";

stringVec[3] = "four";

//cout << "activated crash:" << endl;

//stringVec[4] = "index error";

for(int i=0; i<count+1; i++)

Page 19: Complete Computing Slides

6

cout << stringVec[i] << endl;

system("PAUSE");

return EXIT_SUCCESS;

}

================================================================

// STL Date types: stack, queue, priority queue

#include<stack>

#include<queue>

#include<deque>

#include<list>

#include<vector>

#include<iostream>

using namespace std;

int main()

{

const int w = 5; // width for display

queue<int, list<int> > aQueue; // Queue with List-Container

int numbers[] = {1, 5, 6, 0, 9, 1, 8, 7, 2};

const int count = sizeof(numbers)/sizeof(int);

cout << "Put numbers into queue:" << endl;

for(int i = 0; i < count; ++i)

{

cout.width(w); cout << numbers[i];

aQueue.push(numbers[i]);

}

stack<int> aStack; // use stack container

cout << "\n\nRead numbers from queue (same "

"order)\n and put them into stack:"

<< endl;

while(!aQueue.empty())

{

int Z = aQueue.front(); // read value

cout.width(w); cout << Z;

aQueue.pop(); // delete value

aStack.push(Z);

}

priority_queue<int, vector<int>, greater<int> > aPrioQ;

// greater: small elements first (= high priority)

// less: great elements first

cout << "\n\n read numbers from stack "

"(reversed order!)\n"

"and put them into Priority-Queue:" << endl;

while(!aStack.empty())

{

int Z = aStack.top(); // read value

cout.width(w); cout << Z; // display

aStack.pop(); // delete value

aPrioQ.push(Z);

}

cout << "\n\n read numbers from Priority-Queue"

" (sorted order!)" << endl;

while(!aPrioQ.empty())

{

int Z = aPrioQ.top(); // read value

cout.width(w); cout << Z; // display

Page 20: Complete Computing Slides

7

aPrioQ.pop(); // delete value

}

cout << endl << endl;

system("pause");

return 0;

}

================================================================

/* A set is an accumulation if distinct objects, which are called

elements.

A set is an associative container.

*/

#include <set>

#include <iostream>

using namespace std;

namespace brosig_stl

{

// this template function is no STL algorithm

template<class Container>

void showSequence(const Container& s, const char* sep = " ",

std::ostream& where = std::cout)

{

typename Container::const_iterator iter = s.begin();

while(iter != s.end())

where << *iter++ << sep;

where << std::endl;

}

}

int main()

{

set<int> aSet; // compare object: less<int>()

for(int i = 0; i < 10; ++i) aSet.insert(i);

// no effect despite double insertion !!

for(int i = 0; i < 10; ++i) aSet.insert(i);

brosig_stl::showSequence(aSet); // 0 1 2 3 4 5 6 7 8 9

//---------------------------------------

cout << "Deleting by iterator\n"

"Which element should be deleted? (0..9) " ;

int i; cin >> i;

set<int>::const_iterator iter = aSet.find(i);

if(iter == aSet.end())

{

cout << i << " not found!\n";

}

else

{

/* method 'count' results in either 0 or 1,

so it indicates whether this element is a member of

the set or not.

*/

cout << "There is " << aSet.count(i) // 1

<< " times element " << i << endl;

aSet.erase(iter);

cout << i << " deleted!\n";

cout << "There is " << aSet.count(i) // 0

<< " times element " << i << endl;

}

brosig_stl::showSequence(aSet);

//----------------------------------------

Page 21: Complete Computing Slides

8

cout << "Deleting by value\n"

"Which element should be deleted? (0..9)" ;

cin >> i;

int number = aSet.erase(i);

if(number == 0)

cout << i << " not found!\n";

brosig_stl::showSequence(aSet);

//----------------------------------------

/*

'NumberSet(...)' is not initialized by a loop, but by the range of

its constructor. The iterator is of type 'int*'.

*/

cout << "Call constructor by iterator range\n";

// 2 and 1 are doubled!

int Array[] = { 1, 2, 2, 3, 4, 9, 13, 1, 0, 5};

number = sizeof(Array)/sizeof(Array[0]);

set<int> NumberSet(Array, Array + number);

brosig_stl::showSequence(NumberSet); // 0 1 2 3 4 5 9 13

system("PAUSE");

return EXIT_SUCCESS;

}

======================================================================

/*

Just like set, map is also an associative container. But unlike with set,

keys and data are different.

*/

#include<map>

#include<string>

#include<iostream>

using namespace std;

// comparing object: less<long>()

typedef map<long, string> MapType;

typedef MapType::value_type ValuePair;

int main() {

MapType aMap;

aMap.insert( ValuePair(836, "Andrew"));

aMap.insert( ValuePair(274, "Bernard"));

aMap.insert( ValuePair(260, "Joe"));

aMap.insert( ValuePair(720, "Caren"));

aMap.insert( ValuePair(138, "Thomas"));

aMap.insert( ValuePair(135, "Sean"));

// Xavier will not be added, as

// key already exists.

aMap.insert( ValuePair(720, "Xavier"));

/* Names are printed in the order of their numbers

*/

cout << "Output:\n";

MapType::const_iterator iter = aMap.begin();

while(iter != aMap.end())

{

cout << (*iter).first << ":" // Number

<< (*iter).second // Name

<< endl;

++iter;

}

cout << "Print name after entering number\n"

<< "Number: ";

long Number; cin >> Number;

iter = aMap.find(Number); // O(log N)

if(iter != aMap.end())

Page 22: Complete Computing Slides

9

cout << (*iter).second << " " // O(1)

<< aMap[Number] // O(log N)

<< endl;

else cout << "not found!" << endl;

system("pause");

return 0;

}

=========================================================================

// Function Pointers

#include <iostream>

using namespace std;

int addition (int a, int b)

{ return (a+b); }

int subtraction (int a, int b)

{ return (a-b); }

int operation (int x, int y, int (*functocall)(int,int))

{

int g;

g = (*functocall)(x,y);

return g;

}

int main()

{

int m = operation (7, 5, &addition);

cout <<m << endl;

int n = operation(7,5, &subtraction);

cout <<n << endl;

system("PAUSE");

return 0;

}

========================================================================

Page 23: Complete Computing Slides

Computing Computing –– LectureLecture

(WS 2012/13)(WS 2012/13)University University ofof OldenburgOldenburg

Dipl.-Phys. Ulrich Brosig

Page 24: Complete Computing Slides

LECTURE 0LECTURE 0

Page 25: Complete Computing Slides

Organisational Matters (1)Organisational Matters (1)

� LecturesMonday, 16:15 – 17:45 hrsWednesday, 12:15 – 13:45 hrsWednesday, 12:15 – 13:45 hrsLecture Hall W02 1-143

� ExercisesTuesday, 10:15 – 11:45 hrs(only for students with very little previous knowledge)Wednesday, 14:15 – 15:45 hrsWednesday, 14:15 – 15:45 hrsWednesday, 16:15 – 17:45 hrs(for all students)Lecture Hall W02 2-249

Page 26: Complete Computing Slides

Organisational Matters (2)Organisational Matters (2)

� Lectures are scheduled to start on 22-Oct- 201222-Oct- 2012

� Exercises are scheduled to start on 30-Oct-2012

� Christmas break: 24-Dec-2012 to 05-Jan-2013

� Last lectures / exercises: 06-Feb-2013

(written exam)

Page 27: Complete Computing Slides

Organisational Matters (3)Organisational Matters (3)

� Attainable credit points: 6.00 CP

� Workload: 180 hrs� Workload: 180 hrs

� Time of attendance: 70 hrs

� Literature:

◦ General books on computing and C++

◦ Ulrich Breymann, C++, Eine Einführung, ◦ Ulrich Breymann, C++, Eine Einführung, Hanser Verlag

◦ Bjarne Stroustrup, The C++ Programming Language, Addison-Wesley

Page 28: Complete Computing Slides

Organisational Matters (4)Organisational Matters (4)

� Publically & freely downloadable programs:programs:◦ Compiler (should be run under Windows):

Bloodshed Dev-C++ 5.0 Vers 4.9.9.2http://www.bloodshed.net/MS Visual C++ Express 2010http://www.chip.de/downloads/Visual-C-2010-Express_24081894.html

◦ Structorizer◦ Structorizerhttp://structorizer.fisch.lu/

◦ PAPDesignerhttp://www.gso-koeln.de/papdesigner/Hauptseite.html

Page 29: Complete Computing Slides

Computing As A DisciplineComputing As A Discipline

� The discipline of computing is the systematic study of systematic study of

algorithmic processes that describe and transform information: their

theory, analysis, design, efficiency, implementation, and application. The

fundamental question underlying all fundamental question underlying all computing is "What can be (efficiently)

automated?“(ACM Education Board 1989)

Page 30: Complete Computing Slides

ContentsContents

� The Basics of Computing� A Survey of Programming Languages

� Numbers, characters� Numbers, characters� Algorithms (sequence, selection, iteration)

� Programming language (C++)� Structures of algorithms

� Input/output, pre-processor� Arrays, strings� Functions (procedural programming)� Functions (procedural programming)

� Program files (modular programming)� Introduction into classes (object orientated

programming)

Page 31: Complete Computing Slides

The Basics of ComputingThe Basics of Computing

� What is a computer?

� Types of a computer� Types of a computer

� Parts of a computer

� The basics of information

Page 32: Complete Computing Slides

What is a computer? (1)What is a computer? (1)� In simple terms, a computer is an electronic machine

capable of performing various arithmetic and logical operations. The computer is also capable of storing information, which can be used later.operations. The computer is also capable of storing information, which can be used later.

� A computer can process millions of instructions in a few seconds with high accuracy. Hence a computer can be defined as an automatic electronic machine for performing calculations or controlling operations that are expressible in numerical or logical terms. Computers are very accurate and save time by performing the assigned task very fast.

It is the ability to take instructions in the form of � It is the ability to take instructions in the form of programs and execute them, that distinguishes a computer from a mechanical calculator. While both are able to make computations, a calculator responds simply to immediate input.

Page 33: Complete Computing Slides

What is a computer? (2)What is a computer? (2)

� Computers accept instructions and data, perform arithmetic and logical operations and produce information. The data fed into the produce information. The data fed into the computer is converted into information through processing.

� The first electronic computers were developed in the mid-20th century. These were very huge in size, say, the size of a large room, consuming as much power as several hundred modern personal computers several hundred modern personal computers (PCs). Modern computers based on integrated circuits are billions of times more capable than the early machines, and occupy a fraction of the space.

Page 34: Complete Computing Slides

What is a computer? (3)What is a computer? (3)� Hardware◦ Hardware refers to all the physical components associated

with a computer. The most important is the central processing unit (CPU) or microprocessor. It is the 'brain' of with a computer. The most important is the central processing unit (CPU) or microprocessor. It is the 'brain' of the computer as does all the calculations and processing. Other hardware devices are monitor, keyboard, mouse, printer, hard disk etc.

� Software◦ Software is a set of instructions/programs which enables

the computer to perform a specific task. An important software called the 'Operating System' is a set of specialized programs which manage the overall operations specialized programs which manage the overall operations of the computer. Windows 7/8 is a well-known and widely used operating system. There are other types of software too, known as the application software which are intended to be used for specific tasks such as word processing etc.

Page 35: Complete Computing Slides

What is a computer? (4)What is a computer? (4)� Firmware◦ The basic input/output system (BIOS) is a de

facto standard defining a firmware interface.facto standard defining a firmware interface.

◦ The BIOS software is built into the PC, and is the first code run by a PC when powered on ('boot firmware'). When the PC starts up, the first job for the BIOS is to initialize and identify system devices such as the video display card, keyboard and mouse, hard disk drive, optical disc drive and other hardware. The BIOS then locates boot loader software held on a peripheral device (designated as a 'boot device'), such as a hard disk or a CD/DVD, and loads and executes that software, giving it control of the PC. This process is known as booting, or booting up, loads and executes that software, giving it control of the PC. This process is known as booting, or booting up, which is short for bootstrapping.

◦ BIOS software is stored on a non-volatile ROM chip on the motherboard.

Page 36: Complete Computing Slides
Page 37: Complete Computing Slides

Types of a computerTypes of a computer� Analog Computers

◦ Analog Computer is a computing device that works on continuous range of values. The results given by the analog computers will only be approximate since they deal with quantities that vary continuously. It generally deals with physical variables such as voltage, pressure, temperature, speed, etc.pressure, temperature, speed, etc.

� Digital Computers

◦ On the other hand a digital computer operates on digital data such as numbers. It uses binary number system in which there are only two digits 0 and 1. Each one is called a bit.

◦ The digital computer is designed using digital circuits in which there are two levels for an input or output signal. These two levels are known as logic 0 and logic 1. Digital Computers can give more accurate and faster results.

◦ The digital computer is well suited for solving complex problems in engineering and technology. Hence digital computers have an increasing use in the field of design, research and data processing.

◦ Based on the purpose, digital computers can be further classified as,� General Purpose Computers� General Purpose Computers� Special Purpose Computers

◦ Special purpose computer is one that is built for a specific application. General purpose computers are used for any type of applications. They can store different programs and do the jobs as per the instructions specified on those programs. Most of the computers that we see today, are general purpose computers.

Page 38: Complete Computing Slides

Types of computers based on Types of computers based on

configurationconfiguration� Super Computers

� Mainframe Computers� Mainframe Computers

� Mini Computers

� Micro Computers

� Desktop Computers

� Laptop Computers� Laptop Computers

� Handheld Computers(PDAs)

� Embedded Systems

Page 39: Complete Computing Slides

Parts of a computer (1)Parts of a computer (1)

� CPU(Central Processing Unit)◦ The central processing unit or

the (micro)processor is the core of the computer. It the (micro)processor is the core of the computer. It has the electronic circuitry to process the input data to get the required information. It is the processor which executes the instructions.

� Random Access Memory (RAM)◦ resides inside the system unit and stores the data

that the CPU uses for processing. But this memory is volatile which means that the data will be erased once the computer is switched off.once the computer is switched off.

� Mouse (input device)

� Keyboard (input device)� Monitor (output device)

Page 40: Complete Computing Slides

Parts of a computer (2)Parts of a computer (2)� Storage◦ Hard disk

� Hard Disk Drive stores information on a hard disk with a magnetic � Hard Disk Drive stores information on a hard disk with a magnetic surface. It is normally inside the system unit. In most of the systems, the hard disk acts as the primary storage, storing almost all the program files and other data. Hard disks can store massive amount of information depending upon their configuration.

◦ CD/DVD drive� Most of the computers today come with a CD/DVD Drive which is

located on the front side of the CPU Box. CD drives use lasers to read data from a CD, and if it is a writable CD drive, you can also write data onto CDs.

� DVD Drives are similar to CD Drive, except that the amount of data � DVD Drives are similar to CD Drive, except that the amount of data that a DVD can hold is much more than a CD.

◦ Floppy disk drive (now outdated)

◦ USB stick� act logically as hard disks.

Page 41: Complete Computing Slides

The Basics of Information (1)The Basics of Information (1)

� bit (a contraction of binary digit) ◦ is the basic unit ◦ is the basic unit

of information in computing

◦ it is the amount of information stored by a digital device or other physical system that exists in one of two possible distinct states. � These may be the two stable states of a flip-� These may be the two stable states of a flip-

flop, two positions of an electrical switch, two distinct voltage or current levels allowed by a circuit, two distinct levels of light intensity, two directions of magnetization or polarization, etc.

Page 42: Complete Computing Slides

The Basics of Information (2)The Basics of Information (2)

� byte

◦ is a unit of digital ◦ is a unit of digital information in computing that most commonly consists of eight bits.

◦ is the number of bits used to encode a

single character of text in a computer and for this reason it is the basic addressable for this reason it is the basic addressable element in many computer architectures.

Page 43: Complete Computing Slides

Binary Numeral SystemBinary Numeral System

� The binary numeral system, or base-2 number system, represents numeric number system, represents numeric values using two symbols, 0 and 1. It is a positional notation with a radix of 2◦ Because of its straightforward

implementation in digital electronic circuitry using logic gates, the binary system is used internally by almost all is used internally by almost all modern computers.

◦ For example, the binary number 10102 is equal, in decimal, to (1 × 23) + (0 × 22) + (1 × 21) + (0 × 20), or 1010.

Page 44: Complete Computing Slides

Binary Numeral SystemBinary Numeral System

Page 45: Complete Computing Slides

HexadecimalHexadecimal

� Hexadecimal (also base 16, or hex) is a positional numeral system with a radix, a positional numeral system with a radix, or base, of 16.

� It uses sixteen distinct symbols, most often the symbols 0–9 to represent values zero to nine, and A, B, C, D, E, F to represent values ten to fifteen. ten to fifteen. ◦ For example, the hexadecimal number

2AF316 is equal, in decimal, to (2 × 163) + (10 × 162) + (15 × 161) + (3 × 160), or 10,99510.

Page 46: Complete Computing Slides

Programming LanguageProgramming Language

� A programming language is an artificial language designed to communicate instructions to a computer. communicate instructions to a computer. Programming languages can be used to create programs that control the behaviour of a machine and/or to express algorithms precisely.

� A programming language is usually split into the two components of syntax (form) and semantics (meaning). Most languages and semantics (meaning). Most languages are defined by a specification document (i.e., the C++ programming language is specified by an ISO Standard).

Page 47: Complete Computing Slides
Page 48: Complete Computing Slides

LECTURE 1LECTURE 1

Page 49: Complete Computing Slides

How to get from an idea to a How to get from an idea to a

programprogram� Firstly an idea is developed

� Then this idea is converted to an algorithm� Then this idea is converted to an algorithm

� The algorithm is implemented as a program (source code)

� The source code is given to a computer (i.e. it is edited by a suitable environment)

� The compiler (which is also a program) converts the source code to an executable converts the source code to an executable program

� The executable program is tested on this (or any other) computer.

Page 50: Complete Computing Slides

What is an algorithm?What is an algorithm?

� A set of instructions:

◦ Cooking recipe◦ Cooking recipe

◦ Step-by-step instruction for an assembly

◦ Rules of a game

Page 51: Complete Computing Slides

What is an algorithm?What is an algorithm?

� The characteristics are:

◦ Instruction sequences◦ Instruction sequences

◦ Branching (If-statements)

◦ Instructions that must be repeated (loops)

◦ Imprecise statements

� Generally: a set of statements

Page 52: Complete Computing Slides

What is an algorithm?What is an algorithm?

� Definition: a set of working instructions for solving a problem◦ These instructions must be given very precisely ◦ These instructions must be given very precisely

so that the computer can take proper actions.

� How to write down algorithms?◦ In common speech

◦ In a programming language

◦ In a flow chart

◦ In a structogram◦ In a structogram

� Who / what executes these algorithms?◦ A human being

◦ A computer (quick, reliable, precise)

Page 53: Complete Computing Slides

What is an algorithm?What is an algorithm?

� Example: Calculate the sum of all numbers from 1 to 100numbers from 1 to 100

� In common speech: ◦ “Calculating” means “to add”

◦ Where do we get these numbers from?(in Mathematics: “Axiom of Choice”)

◦ Which numerical system is to be used?

� More precisely: add all integer numbers from 1 to 100 which are given by the system.

Page 54: Complete Computing Slides

FlowchartFlowchart

� Example: A flowchart for computing factorial N A flowchart for computing factorial N

(n!)e.g.

10! = (1*2*3*4*5*6*7*8*9*10)in a non-recursive way.

Page 55: Complete Computing Slides

FlowchartFlowchart

Page 56: Complete Computing Slides

Flowchart symbolsFlowchart symbols

� Start and end symbols are represented as circles, ovals or rounded rectangles, usually containing the word "Start" or "End", or another containing the word "Start" or "End", or another phrase signalling the start or end of a process.

� Arrows showing what is called "flow of control" in computer science. An arrow coming from one symbol and ending at another symbol represents that control passes to the symbol the arrow points to.

� Processing steps are represented as rectangles. � Processing steps are represented as rectangles.

� Input / Output is represented as a parallelogram.

Page 57: Complete Computing Slides

Flowchart symbolsFlowchart symbols

� Conditional or decision is represented as

a diamond (rhombus) showing where a a diamond (rhombus) showing where a

decision is necessary, commonly a

Yes/No question or True/False test. The

conditional symbol is unique in that it has

two arrows coming out of it, usually from

the bottom point and right point, one the bottom point and right point, one

corresponding to Yes or True, and one

corresponding to No or False. (The

arrows should always be labelled.)

Page 58: Complete Computing Slides

NassiNassi--ShneidermanShneiderman--DiagramDiagram

� Developed in 1972 by Isaac Nassi and Ben Shneiderman, these diagrams are also called structograms, as they show a program's structograms, as they show a program's structures.

� Following a top-down design, the problem at hand is reduced into smaller and smaller subproblems, until only simple statements and control flow constructs remain. Nassi–Shneiderman diagrams reflect this top-down decomposition in a straight-forward way, using nested boxes to represent subproblems. decomposition in a straight-forward way, using nested boxes to represent subproblems. Consistent with the philosophy of structured programming, Nassi–Shneiderman diagrams have no representation for a GOTO or JUMP statement.

Page 59: Complete Computing Slides

NassiNassi--ShneidermanShneiderman--DiagramDiagram

� Process blocks: the process block represents the simplest of steps and represents the simplest of steps and

requires no analyses. When a process block is encountered the action inside

the block is performed and we move onto the next block.

Page 60: Complete Computing Slides
Page 61: Complete Computing Slides

NassiNassi--ShneidermanShneiderman--DiagramDiagram

� Branching blocks: there are two types of branching blocks. First is the types of branching blocks. First is the simple True/False or Yes/No branching block which offers the program two paths to take depending on whether or not a condition has been fulfilled. These blocks can be used as a looping procedure stopping used as a looping procedure stopping the program from continuing until a condition has been fulfilled.

Page 62: Complete Computing Slides
Page 63: Complete Computing Slides

NassiNassi--ShneidermanShneiderman--DiagramDiagram

� The second type of branching block is a multiple branching block. This a multiple branching block. This

block is used when a select case is needed in a program. The block

usually contains a question or select case. The block provides the program

with an array of choices and is often with an array of choices and is often used in conjunction with sub process

blocks to save space.

Page 64: Complete Computing Slides
Page 65: Complete Computing Slides

NassiNassi--ShneidermanShneiderman--DiagramDiagram� Loops: this block allows the program to loop one or a

set of process until a particular condition is fulfilled. The process blocks covered by each loop are subset with a side-bar extending out from the condition.process blocks covered by each loop are subset with a side-bar extending out from the condition.

� There are two main types of testing loops, test first and test last blocks. The only difference between the two is the order in which the steps involved are completed. In the test first situation, when the program encounters the block it tests to see if the condition is fulfilled, then, if it is not completes the process blocks and then loops back. The test is performed again and, if the condition is still unfulfilled, the processes again. If at any stage the still unfulfilled, the processes again. If at any stage the condition is fulfilled the program skips the process blocks and continues onto the next block.

Page 66: Complete Computing Slides
Page 67: Complete Computing Slides
Page 68: Complete Computing Slides

ProcessProcess ofof compilationcompilation

Page 69: Complete Computing Slides

General structure of a C++ General structure of a C++

programprogram

Page 70: Complete Computing Slides

Structure of a simple C++ Structure of a simple C++

programprogram

// C++ programcomment

pre-

processor

directive

// C++ program#include <iostream>

using namespace std;

int main(){

cout << “Hallo Welt” << endl;

library

namespace

Start of

main

program

system("PAUSE");

return 0;}

Print character

string and add

new line

Wait for

keystroke

End of

progra

m

Page 71: Complete Computing Slides

LECTURE 2LECTURE 2

Page 72: Complete Computing Slides

Structure of a simple C++ Structure of a simple C++

programprogram� #include

◦ Includes library needed for processing the code.

� int main( )

◦ Denotes main program. The program’s code is enclosed by curly brackets { }. Both the empty round brackets and the curly brackets are mandatory.

� int

◦ The main program returns an integer number (“0” in case of successful termination).

� Each line of code is terminated by a semicolon ;

Page 73: Complete Computing Slides

Structure of a simple C++ Structure of a simple C++

programprogram� cout◦ Outputs values to standard device (i.e.

screen). The << operator shifts characters to screen). The << operator shifts characters to output device.

� A new line is produced by◦ cout << endl; or◦ cout << ‘\n’; or◦ cout << “(seq. of characters)\n”;

� cin� cin◦ Is standard input statement. The >> operator

shifts typed-in character to variable.cin >> variable1 >> variable2;

Page 74: Complete Computing Slides

Structure of a simple C++ Structure of a simple C++

programprogram

#include <iostream>using namespace std ;using namespace std ;int main (){

float a, b, f;cout << ”Input a: ”; cin >> a;cout << ”Input b: ”; cin >> b;f = a * b;cout << ”Area: ”<< f << endl;

system(“pause“);return 0;

}

Page 75: Complete Computing Slides

BasicsBasics

� Allowed characters

◦ Small letters◦ Small letters

◦ Capital letters

� C++ is case sensitive !! (i.e. there is a

difference between small and capital letters)

◦ Numerals

◦ Special characters◦ Special characters

� + - * / = [ ] { } ( ) % & _ | \ < > ! ? ~ # ^ . , : ; ‘ “

Page 76: Complete Computing Slides

BasicsBasics

� Identifiers◦ Are case sensitive

◦ Start with a letter or underscore ( _ )◦ Start with a letter or underscore ( _ )

◦ Are not limited in length.

◦ Must be different from keywords.

� Variables◦ Must be declared before use.int sum, result;◦ Need not be initialized.double value = 3.4;double value = 3.4;bool flag = false;◦ If they are not initialized, they may adopt any value.

◦ Good programming style: whenever possible, please use descriptive (self-documenting) variable identifiers.

Page 77: Complete Computing Slides

KeywordsKeywords

Page 78: Complete Computing Slides

Simple data typesSimple data types

Page 79: Complete Computing Slides

Simple data typesSimple data types

Page 80: Complete Computing Slides

Scope, validity, and visibility of Scope, validity, and visibility of

variablesvariables

Page 81: Complete Computing Slides

Scope, validity, and visibility of Scope, validity, and visibility of

variablesvariables� Global variables can be referred

anywhere in the code.anywhere in the code.

� The scope of the local variables is limited to the code level in which they are declared. If they are declared at the beginning of a function (like in main) its scope is a function (like in main) its scope is the whole main function.

� Good programming style: try to avoid global variables as much as possible.

Page 82: Complete Computing Slides

Scope, validity, and visibility of Scope, validity, and visibility of

variablesvariables� The scope of a variable is given by

the block in which it is declared (a the block in which it is declared (a

block is a group of instructions grouped together within curly brackets

{ }). If it is declared within a function it will

be a variable with function scope, if it be a variable with function scope, if it is declared in a loop its scope will be

only the loop, etc...

Page 83: Complete Computing Slides

30.10.2012

1

LECTURE 3LECTURE 3

ConstantsConstants

� A constant is any expression that has a fixed value. They can be divided in Integer Numbers, Floating-Point Numbers, Characters and Strings.

� Declared constants can be written using ‘const ’const double pi = 3.14159;◦ Constants cannot be changed.� If the programmer tries to alter its value, an

error arises.

ConstantsConstants

� There are some pre-defined constants

that can be treated like escape-codes:

ConstantsConstants

� Your own names can be defined for constants often used without having to resource to variables; simply by use the #define pre-processor directive. #define identifier value

� E.g. when the pre-processor directives (defined constants)#define PI 3.14159265 #define NEWLINE '\n’are used, the following program code can be written:circle = 2 * PI * r; cout << NEWLINE;

� Good programming style: write constants with capital letters, so they can easily be detected.

Basic operatorsBasic operators

� General = (assignment)

� Arithmetic

+ (addition)

- (subtraction)* (multiplication)

/ (division)

% (modulo)

� Logic&& (AND)

|| (OR)

! (NOT)

== (EQUAL)!= (NOT EQUAL)

Basic Basic operatorsoperators

� (7 == 5) would return false.

� (5 > 4) would return true.

� (3 != 2) would return true.

� (6 >= 6) would return true.

� (5 < 5) would return false.

Page 84: Complete Computing Slides

30.10.2012

2

Basic Basic operatorsoperators

� Suppose that a=2, b=3 and c=6

� (a == 5) would return false.

� (a*b >= c) would return true

since (2*3 >= 6) is true

� (b+4 > a*c) would return false

since (3+4 > 2*6) is true

� ((b=2) == a) would return true.

Special Special operatorsoperators

� Increasea++; (Suffix)++a; (Prefix)a += 1;a = a + 1;

b=3;a = ++b;// a is 4// b is 4

b=3; a=b++;// a is 3// b is 4

� Decreasea-- ; --a;a -= 1;a = a – 1;

Special Special operatorsoperators

� Multiplicationa *= 6;a = a *6;

� Divisiona /= 6;a = a/6;

Control structures (Control structures (ifif))

if ( <expression> ) <statement1>;

if ( <expression> ) <statement1>;

else <statement2>;

if ( <expression> ){

<statement1>;<statement2>;<statement3>;

}else{

<statement4>;<statement5>;

}if ( <expression> ){

<statement1>;<statement2>;<statement3>;

}

Control structures (Control structures (switchswitch))

switch (<expression>){case <constant1> :<block of instructions 1>break;

case <constant2> :<block of instructions 2>break;

default:<default block of instructions>

}

Control structures (Control structures (switchswitch))� It works in the following way: switch evaluates

expression and checks if it is equivalent to <constant1>, if it is, it executes <block of instructions 1> until it finds the break keyword, at which the program will jump to the end of the switch selective structure.

� If <expression> is not equal to <constant1> it will check if expression is equivalent to <constant2>. If it is, it will execute <block of instructions 2> until it finds the break keyword.

� Finally, if the value of expression has not matched any of the previously specified constants (you may specify as many case sentences as values you want to check), the program will execute the instructions included in the default section, if this exists, since it is optional.

Page 85: Complete Computing Slides

30.10.2012

3

Control structures (Control structures (whilewhile))

while (< expression>) <statement>;

while (<expression>){

<statement1>;<statement1>;<statement1>;

}

do{

<statement1>;<statement1>;<statement1>;

} while (<expression>);

Control structures (Control structures (forfor))

for (< initialization>; <condition>; <increase>) <statement>;

for (< initialization>; <condition>; <increase>){

<statement1>;<statement1>; <statement1>;

}

Page 86: Complete Computing Slides

04.11.2012

1

LECTURE 4LECTURE 4

FunctionsFunctions

� Using functions we can structure our

programs in a more modular way.

� A function is a block of instructions

that is executed when it is called from

some other point of the program.

FunctionsFunctions

type name (<argument1>, <argument2>,…){

<statement1>;<statement2>;<statement3>;

…}

type name (){

<statement1>;<statement2>;<statement3>;

…}

FunctionsFunctions� type is the type of data returned by the function.

� The type of functions which do not return a value is void.

� name is the name by which the function is called.

� arguments (as many can be specified as necessary). ◦ Each argument consists of a type of data followed by a

particular name, like in a variable declaration (for example, int x ) and which acts within the function like any other variable. They serve to allow passing parameters to the function when this one is called. The different parameters are separated by commas.

◦ There may be no arguments at all.

� statement is the function's body. It can be a single instruction or a block of instructions. In latter case it must be delimited with curly brackets signs { }.

FunctionsFunctions

� Functions may be used like

subprograms when not applied in an

object-orientated environment.

� Functions also serve as methods to a

class or an object when applied in an

object-orientated environment.

(� cf. lectures to come)

FunctionsFunctions

� Let’s see how it works: The main function begins by declaring the variable z of type int. Just after that we see a call to the addition function.

� The parameters have a clear correspondence. Within the main function we call the addition function passing two values: 5 and 3 which correspond with the int a and int b parameters declared for the addition function. The value of both parameters passed in the call are copied to the local variables a and b within the function.

� Function addition declares a new variable (int r;), and by means of the expression r=a+b ;, it assigns to r the result of a plus b. Because the passed parameters for a and b are 5 and 3 respectively the result is 8.

Page 87: Complete Computing Slides

04.11.2012

2

FunctionsFunctions

The following line of code:return (r);finalizes function addition, and returns

the control back to the function that

has called it (main) following the

program by the same point in which it

was interrupted by the call to addition. Additionally, return was called at the

end of the function with the content of

variable r (return (r);),

which at that moment was 8, so this

value is said to be returned by the

function.

The value returned by a function is the

value given to the function when it is

evaluated. Therefore, z will store the

value returned by addition (5, 3), that

is 8.

FunctionsFunctions� Following, we have the function subtraction. The only thing that this function

does is to subtract both passed parameters and to return the result.

� Nevertheless, if we examine the function main we will see that we have

made several calls to function subtraction. We have used some different

calling methods so that you see other ways or moments when a function can

be called.

FunctionsFunctions

� Important: Until now, in all functions we have seen, all the parameters passed to the functions have been passed by value. This means that when calling a function with parameters, that which we have passed to the function were values but never the specified variables themselves.

FunctionsFunctions

� Wouldn’t it be interesting to

manipulate the value of an external

variable from inside a function.

� To make that work we will have to use

arguments passed by reference, as

in the function duplicate of the

following example:

FunctionsFunctions FunctionsFunctions

� Here, the ampersand sign & serves to indicate that the variable has to be passed by reference.

� Strictly speaking, the & sign denotes the address of the variable passed, and not its value.◦ When passing a variable by reference we

are passing the variable itself and any modification that we do to that parameter within the function will have effect in the passed variable outside it.

Page 88: Complete Computing Slides

04.11.2012

3

FunctionsFunctions

� Passing by reference

is an effective way to

allow a function to

return more than one

single value.

� For example, now

comes a function

that returns the

previous and next

numbers of the first

parameter passed.

FunctionsFunctions

FunctionsFunctions

� When defining a function we can specify default values that will be taken by

the argument variables in case that these are avoided when the function is called. The way to do so is simply

by assigning a value to the arguments when declaring the function.

FunctionsFunctions

� Functions can be overloaded.◦ In this case we

defined two functions with the same name, but one of them accepts two arguments of type int and the other accepts them of type float .

FunctionsFunctions

� Recursivefunctions are

those which

are called by

themselves.

Page 89: Complete Computing Slides

05.11.2012

1

LECTURELECTURE 55

ArraysArrays

� Arrays are a series of elements (variables) of the same type placed consecutively in memory that can be individually referenced by adding an index to a unique name.

� For example, an array to contain 5 integer values of type intcalled billy could be represented this way:

� NOTE: The elements field within brackets [ ] when declaring an array must be a constant value, since arrays are blocks of static memory of a given size and the compiler must be able to determine exactly how much memory should be assigned to the array before any instruction is executed.

ArraysArrays

� Initializing arrays (1)

◦ When declaring an array of local scope (within a function), if we

do not specify otherwise, it will not be initialized, so its content is

undetermined until we store some values in it.

◦ If we declare a global array (outside any function) its content will

be initialized with all its elements filled with zeros. Thus, if in the

global scope we declare: int billy [5];every element of billy will be set initially to 0:

ArraysArrays

� Initializing arrays (2)

◦ Additionally, when we declare an array, we have the possibility to assign initial values to each one of its elements using key brackets { }. For example:int billy [5] = { 16, 2, 77, 40, 12071 };

ArraysArrays

� Access to the values of an array

◦ In any point of the program in which the array is visible we can access individually anyone of its values for reading or modifying it as if it was a normal variable. The format is the following one: name[index]

ArraysArrays

Arrays as parametersArrays as parameters� In C++ is not possible to pass by value a complete

block of memory as a parameter, even if it is ordered as an array, to a function, but it is allowed to pass its address.

� In order to admit arrays as parameters the only thing that must be done when declaring the function is to specify in the argument the base type for the array that it contains, an identifier and a pair of void brackets [ ].

� For example, the following function:void procedure (int arg[])

admits a parameter of type "Array ofchar" called arg. In order to pass to this function an array declared as:

int myarray [40]; it would be enough with a call like this:

procedure (myarray);

Arrays Arrays -- BubblesortBubblesort

Page 90: Complete Computing Slides

11.11.2012

1

LECTURE 6LECTURE 6

CharacterCharacter stringsstrings

� In C++ there is no specific elemental variable type to store strings of characters. In order to fulfill this feature we can use arrays of type char, which are successions of char elements. Remember that this data type (char) is the one used to store a single character, for this reason an array of char is used to make strings of single characters.

CharacterCharacter stringsstrings

� How long should such an array

generally be? Its maximum size does

not have to be always fully used.

� Therefore, since the array of

characters can store shorter strings

than its total length, there is a

convention to end the valid content of

a string with a null character, whose

constant can be written 0 or '\0'.

Character stringsCharacter strings

� Notice how after the valid content

there is included a null character ('\0')

in order to indicate the end of string.

The panels in gray colour represent

indeterminate values.

Character stringsCharacter strings

� Initialization of strings◦ Because strings of characters are ordinary

arrays they all fulfill the same rules. For example, if we want to initialize a string of characters with predetermined values we can do it in a similar way to any other array:char mystring[] = {‘H’,’e’,’l’,’l’,’o’,’\0’};

◦ In this case we would have declared a string of characters (array) of 6 elements of type char initialized with the characters that compose Hello plus a null character '\0'.

Character stringsCharacter strings

� Initialization of strings

◦ Instead of initializing a string in such a

rather complicated way, we can write:char mystring[] = “Hello”;

◦ Notice : we can "assign" a multiple

constant to an array only at the moment of

initializing it.

Page 91: Complete Computing Slides

11.11.2012

2

Character stringsCharacter strings

� Input strings from keyboard◦ When cin is used with strings of characters it is

usually used with its getline method, which can be called following this prototype:

cin.getline ( char buffer[], intlength, char delimiter = ‘ \n');

where buffer is the address where to store the input (like an array, for example), length is the maximum length of the buffer (the size of the array) and delimiter is the character used todetermine the end of the user input, which by default - if we do not include that parameter - will be the newline character ('\n').

Character stringsCharacter strings

� We could also have written:cin >> mybuffer;

� This method has the following limitations that cin.getline has not:◦ It can only receive single words (no complete

sentences) since this method uses as delimiter any occurrence of a blank character, including spaces, tabulators, newlines and carriage returns.

◦ It is not allowed to specify a size for the buffer. What makes your program unstable in case that the user input is longer than the array that will host it.

� For these reasons it is recommendable that whenever you require strings of characters coming from cin you use cin.getline instead of cin >>.

Character stringsCharacter strings

� Converting strings to other types:

◦ atoi converts string to int type.

◦ atol converts string to long type.

◦ atof converts string to float type.

Character stringsCharacter stringsManipulating strings:

strcat: char* strcat (char* dest, const char* src);

Appends src string at the end of dest string. Returns dest.

strcmp: int strcmp (const char* string1, const char* string2);

Compares strings string1 and string2. Returns 0 is both strings are equal.

strcpy: char* strcpy (char* dest, const char* src);

Copies the content of src to dest. Returns dest.

strlen: size_t strlen (const char* string);

Page 92: Complete Computing Slides

11.11.2012

1

LECTURELECTURE 77

PointersPointers

� Address (dereference) operator (&)It is used as a variable prefix and can be translated as "address of", thus: & variable1 can be read as "address of variable1“

� Reference operator (*)It indicates that what has to be evaluated is the content pointed by the expression considered as an address. It can be translated by “value pointed by“.* mypointer can be read as "value pointed by mypointer".

PointersPointers PointersPointers

� Declaring variables of type pointer

◦ Due to the ability of pointers to reference

directly to the value where they point to it becomes necessary to specify which data

type a pointer points to when declaring it,

since it is not the same to point to a char

than to an int or a float type.

Pointers and arraysPointers and arraysThe identifier of an array is equivalent to the address of its first element, like a pointer is equivalent to the address of the first element that it points to, so in fact they are the same thing. For example, supposing these two declarations:

int numbers [20];int * p;

the following allocation would be valid:

p = numbers;At this point p and numbers are equivalent and they have the same properties, with the only difference that we could assign another value to the pointer p whereas numbers will always point to the first of the 20 integer numbers of type int it was defined with. So, unlike p, which is an ordinary variable pointer, numbers is a constant pointer (indeed this is an Array: a constant pointer). Therefore, although the previous expression was valid, the following allocation is not:

numbers = p;because numbers is an array (constant pointer), and no values can be assigned to constant identifiers.

Pointers to pointersPointers to pointers

� C++ allows the use of pointers that point to other pointers. In order to do that we only need to add an asterisk (*) for each

level of reference:

◦ char a;

◦ char * b;

◦ char ** c;

◦ a = 'z';

◦ b = &a;

◦ c = &b;

� this, supposing random memory locations 7230, 8092 and 10502, could be described thus:

Page 93: Complete Computing Slides

11.11.2012

2

voidvoid pointerspointers

� void pointers can point to any data type, from an integer value or a float to a string of characters.

� Its sole limitation is that the pointed data cannot be referenced directly (we cannot use reference asterisk * operator on them), since its length is always undetermined, and for that reason we will always have to resort to type casting or assignations to turn our void pointer to a pointer of a concrete data type that we can refer.

Pointers to functionsPointers to functions

� Pointers to functions are used for passing a function as a parameterto another function, since these cannot be passed dereferenced.

� In order to declare a pointer to a function we must declare it like the prototype of the function but enclosing between parenthesis ( ) the name of the function and inserting a pointer asterisk (*) before.

Dynamic memoryDynamic memory

� Until now, in our programs, we have only

had as much memory as we have requested in declarations of variables,

arrays and other objects that we included, having the size of all of them to

be fixed before the execution of the program.

� But what if we need a variable amount of memory that can only be determined

during the execution of a program?

Dynamic memory Dynamic memory -- newnew

� In order to request dynamic memory there exists the operator new.

� new is followed by a data type and

optionally the number of elements

required within brackets [ ].

� new returns a pointer to the beginning

of the new block of assigned memory.

Dynamic memory Dynamic memory -- newnew

pointer = new type

pointer = new type [elements]

int * amount;amount = new int [5];

int * amount = new int[5];

Dynamic memory Dynamic memory -- newnew

� What is the difference between declaring a normal array and assigning memory to a pointer?◦ The most important difference is that the

size of an array must be a constant value, which limits its size to what we decide at the moment of designing the program before its execution, whereas the dynamic memory allocation allows to assign memory during the execution of the program.

Page 94: Complete Computing Slides

11.11.2012

3

Dynamic memory Dynamic memory -- newnew

� The dynamic memory is generally managed by the operating system; there is a possibilityfor the memory to exhaust.

� If this happens, i.e. if the operating system cannot assign the memory we request using the operator new, a null pointer (NULL) will be returned.

� NULL is a constant value defined in many C++ libraries specially designed to indicate null pointers.

◦ In case this constant is not defined you can do it yourself by defining it to 0.

Dynamic memory Dynamic memory -- newnew

int * amount;… … … amount = new int [5];if (amount == NULL) {

// error message// take measures

}

Dynamic memory Dynamic memory -- deletedelete

� If a dynamic variable is no longer

needed it shall be freed so that its

dynamic memory will become

available for future requests. For this

there exists the operator delete.

delete pointer;

delete [ ] pointer;

Dynamic memory Dynamic memory -- deletedelete

� Important:

◦ delete may only be applied once to a

dynamic data object.

◦ delete may only be applied to dynamic

data objects which have previously been declared with new.

◦ If these rules are not obeyed, runtime

errors may occur.

Data structuresData structures

� A data structure is a set of diverse types of data that may have different lengths grouped together under a unique declaration. Its form is the following:

� object_name may be omitted.

� A structure need not have a name. In this case it is called an anonymous structure.

struct model_name

{

type1 element1;

type2 element2;

type3 element3;

.

.} object_name;

Data structuresData structures

� Data structure elements are accessed

by

object_name.element1object_name.element2

object_name.element3

….

Page 95: Complete Computing Slides

11.11.2012

4

Data structuresData structures

� Pointers to structures

◦ dynamical structures can be pointed at. The

rules are the same as for any fundamental data type: The pointer must be declared as a pointer to the structure.

◦ Dynamical structure elements are accessed by

object_name -> element1object_name -> element2

object_name -> element3

….

Page 96: Complete Computing Slides

19.11.2012

1

LECTURE 8LECTURE 8

Data structures Data structures –– Linked ListsLinked Lists

� In the next two examples, data structures are used to build Linked Lists.◦ The first example shows a solution to the so-

called ‘Josephus Problem’.� In computer science and mathematics, the Josephus

problem (or Josephus permutation) is a theoretical problem related to a certain counting-out game.

� The problem is about people standing in a circle waiting to be executed. After the first person is executed, a certain number of people are skipped and one person is executed. Then again, people are skipped and a person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom.

� The task is to choose the place in the initial circle so that you are the last one to survive.

Data structures Data structures –– Linked ListsLinked Lists

� The second example shows how to construct a Stack as a Linked List.

◦ A stack is a last in, first out data structure.

◦ A stack can have any abstract data type as an element, but

is characterized by only two fundamental operations: push

and pop. The push operation adds to the top of the list, hiding any items already on the stack. The pop operation

removes an item from the top of the list, and returns this

value to the caller.

ClassesClasses

� A class is a logical method to organize

data and functions in a structure.

◦ They are declared using keyword class,

whose functionality is similar to the one of

the keyword struct, but with the possibility

of including functions as members, which

is more than only including data.

ClassesClasses� Classes must have names.

� Classes can be considered user-defined types.

� The body of the declaration can contain members, which can be either data or function declarations, and optionally permission labels, which can be any of these three keywords:◦ private:

◦ public:

◦ protected:

� Data are called member variables, (or sometimes properties), functions are called methods or member functions.

� Any class can instantiate an unlimited number of objects.

� An object can be instantiated statically or dynamically.

ClassesClasses

� Constructors (1)◦ Objects generally need to initialize variables

or to assign dynamic memory during their process of creation to avoid returning unexpected values during their execution.◦ In order to avoid this, a class can include a

special function: a constructor.◦ A constructor can be declared by naming a

member function with the same name as the class. ◦ A constructor has no return value.◦ The constructor will be called automatically

when a new instance of the class is created.

Page 97: Complete Computing Slides

19.11.2012

2

ClassesClasses

� Destructors

◦ The destructor is automatically called when an object is released from the memory.

◦ The destructor must have the same name as the class with a tilde (~) as prefix and it must return no value.

◦ There can only be one destructor, i.e. overloading destructors is not possible.

◦ Destructors can be empty.

◦ The use of destructors is specially suitable when an object assigns dynamic memory during its life, and at the moment of being destroyed we want to release the memory it has used.

ClassesClasses

� Constructors (2)

◦ Overloading Constructors

� Like any other function or method, constructors can be overloaded, too.

◦ Different kinds of constructors

� If we declare a class and do not specify any

constructor the compiler automatically assumes two overloaded constructors:

� Empty constructor

� Copy constructor

ClassesClasses

� Constructors

◦ Of course, all these various kinds of

constructors can be written by the

programmer

� Standard constructor

� List constructor

� The list of parameters is separated from the name of

the constructor by using a single colon :

� Copy constructor

◦ as they serve different purposes.

ClassesClasses

� Useful hint:

◦ When writing a C++ program

professionally, the code of member

functions is separated from their

definitions.

◦ In this case the name of the class

(namespace) is placed in front of the

function name separated by a double

colon ::

Inheritance between classesInheritance between classes

� An important feature of classes is

inheritance. This allows us to create

an object derived from another one,

so that it may include some of the

other's members plus its own ones.

Page 98: Complete Computing Slides

26.11.2012

1

LECTURE 9LECTURE 9

PolymorphismPolymorphism

� Polymorphism is a feature that allows values of different data types to be handled using a uniform interface.

� The concept of parametric polymorphism applies to both data types and functions. ◦ A function that can evaluate to or be applied

to values of different types is known as a polymorphic function.

◦ A data type that can appear to be of a generalized type (e.g., a list with elements of arbitrary type) is designated polymorphic data type like the generalized type from which such specializations are made.

PolymorphismPolymorphism

� Next there is as an example for class

(data type)

polymorphism

◦ Here, Employee is the base class that inherits to all the other three classes.

TemplatesTemplates

� Templates are a feature of the C++programming language that allow functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.◦ Templates are of great utility to

programmers in C++, especially when combined with multiple inheritance

LECTURELECTURE 1010

ContainersContainers

� A container is a class whose instances are collections of other objects.

� Container classes usually implement structures such as a list, map, set, vector, or tree.

� A container class is usually able to store an arbitrary number of data items, i.e. the size of the collection is adjusted automatically.

� The Standard Template Library (STL) contains the implementation of all C++ containers.

� An iterator is an object that allows a programmer to traverse through all the elements of a container, regardless of its specific implementation.

Page 99: Complete Computing Slides

26.11.2012

2

Containers (examples)Containers (examples)

� A vector is a dynamic array.

◦ In order to access a vector, we can use

indexes or iterators.

vectorsvectors

� Useful member functions of vectors are:

◦ iterators

begin( ): Return iterator to beginning

end( ): Return iterator to end

◦ capacity:size( ): Return size

resize( ): Change size

capacity( ): Return size of allocated storage

capacity

empty ( ): Test whether vector is empty

reserve( ): Request a change in capacity

Containers: iteratorsContainers: iterators

� An iterator is any object that, pointing to some element in a range of elements (such as a container), has the ability to iterate through the elements of that range using a set of operators (at least, the increment (++) and dereference (*) operators).

� Each container type (such as a vector) has a specific iterator type designed to iterate through its elements in an efficient way.

UserUser--defined data typesdefined data types

� C++ allows us to define our own types

based on other existing data types. In

order to do that we shall use keyword typedef, whose form is:

typedef existing_type new_type_name;

◦ where existing_type is a C++ fundamental

or any other defined type and

new_type_name is the name that the new type we are going to define.

UserUser--defined data typesdefined data types

� Examples

◦ typedef char C;

◦ typedef unsigned int WORD;

◦ typedef char * String;

◦ typedef char field [50];

Exception handlingException handling

� During the development of a program, there may be some cases where it is not sure whether a piece of the code will work correctly, ◦ either because it accesses resources that do not exist

◦ or because it gets out of an expected range, etc...

� This type of anomalous situations are included in what we consider exceptions and C++ has incorporated three operators to help us to handle these situations: ◦ try

◦ throw

◦ catch

Page 100: Complete Computing Slides

26.11.2012

3

Exception handlingException handling

� The code within the try block is executed normally. In case that an exception takes place, this code must use throw keyword and a parameter to throw an exception. The type of the parameter details the exception and can be of any valid type.

� If an exception has taken place, i.e. if it has been executed a throw instruction within the try block, the catch block is executed receiving as parameter the exception passed by throw.

� There can also be multiple catch blocks.

try {// code to be triedthrow exception;}catch (type exception){// code to be executed in //case of exception}

Exception handlingException handling

� Some functions of the standard C++ language library send exceptions that can be captured if we include them within a try block.

� These exceptions are sent with a class derived from std::exception.

� This class (std::exception) is defined in the C++ standard header file <exception> and serves as pattern for the standard hierarchy of exceptions.

Input / Input / OutputOutput File HandlingFile Handling

� C++ incorporates support for input and

output with files by the use of the

following classes:

◦ ofstream: File class for writing operations

(derived from ostream)

◦ ifstream: File class for reading operations

(derived from istream)

◦ fstream: File class for both reading and

writing operations (derived from iostream)

Opening a fileOpening a file

� The first operation generally done on

an object of one of these classes is to

associate it to a real file.

◦ The open file is represented within the

program by the stream (the object of one

of these classes) and any input or output

performed on it will apply to the physical file.

Opening a fileOpening a file

void open (const char * filename, openmode mode);

This is done by:

mode is a combination ofthese flags:

Closing a fileClosing a file

� When reading to a file, or writing on a

file we must close it so that it becomes

available again.

� The member function close( ) flushes

the buffers and closes the file.

void close ();

Page 101: Complete Computing Slides

26.11.2012

4

Text mode filesText mode files

� Generally, text files are used in the

same way as it done for the

communication with console.

◦ Like in the following example, where we

use the overloaded insertion operator <<

State flagsState flags� bad()◦ Returns true if any failure occurs in a reading or writing

operation.

� fail()◦ Returns true in the same cases as bad() and additionally in

case of a format error.

� eof()◦ Returns true if a file opened for reading has reached the

end.

� good()◦ Returns true if no failure has occurred during operation.

� In order to reset the state of the flags checked by the previous member functions you can use the member function clear().

Stream pointersStream pointers

� All the i/o streams at least have one

stream pointer :

◦ ifstream, like istream, has a pointer known

as get pointer that points to the next

element to be read.

◦ ofstream, like ostream, has a pointer put

pointer that points to the location where

the next element is to be written.

◦ fstream, like iostream, has both: get and

put

Stream pointersStream pointers

� These stream pointers can be read and/or manipulated using the following member functions:

� tellg() and tellp()◦ These two member functions do not have any

parameter and return a value of type pos_type(according ANSI-C++ standard) that is an integer data type representing the current position of get stream pointer (in case of tellg) or put stream pointer (in case of tellp).

� seekg() and seekp()◦ This pair of functions serves to change the

position of stream pointers get and put respectively .

Stream pointersStream pointers

� Both functions are overloaded with two different prototypes:

◦ seekg ( pos_type position );

◦ seekp ( pos_type position );

� This prototype serves to change the stream pointer to an absolute

position from the beginning of the file.

◦ seekg ( off_type offset, seekdir direction );

◦ seekp ( off_type offset, seekdir direction );

� Using this prototype, there can be specified an offset from a concrete

point determined by parameter direction:

Stream pointersStream pointers

� The following example uses the

member functions just seen to obtain

the size of a binary file: