an introduction to c++ lecture 03: loops & containersekprwolf/teaching/... · an introduction...

Post on 17-Aug-2020

2 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

INSTITUTE OF EXPERIMENTAL PARTICLE PHYSICS (IEKP) – PHYSICS FACULTY

An Introduction to C++

Lecture 03: Loops & containers

Roger Wolf16. Mai 2018

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

INSTITUTE OF EXPERIMENTAL PARTICLE PHYSICS (IEKP) – PHYSICS FACULTY

Part 1:

What you need to know about loops

1/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Groundhog day

● One of the main arguments to write (scientific) code is to repeat certain processes (most of the time really often… )

● Examples:

● C(++) offers several ways to do this…

● Numerical integration

● Statistical ensemble tests

● Characterization of large datasets

● Manipulation of large lists

● …

2/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-01: while(...)

● The first method that we will discuss is the while(…) loop:

3/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-01: while(...)

● The first method that we will discuss is the while(…) loop:

Conditional (break) statement

2/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-01: while(...)

● The first method that we will discuss is the while(…) loop:

i is first incremented and then printed

Conditional (break) statement

2/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-01: while(...)

● The first method that we will discuss is the while(…) loop:

● The conditional statement in while(…) is accessed first. If it fails the command block will not be entered.

● In this example we count from 1 to 10 (→ try it yourself).

i is first incremented and then printed

Conditional (break) statement

2/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-01: while(...)

● The first method that we will discuss is the while(…) loop:

● The conditional statement in while(…) is accessed first. If it fails the command block will not be entered.

● In this example we count from 10 to 1 (→ try it yourself).

i is first printed and then decremented

3/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-02: do(...)

● You can also use a loop that accesses the command block first:

● Here the command block will be accessed before the conditional statement will be evaluated.

4/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-02: do(...)

● You can also use a loop that accesses the command block first:

● Here the command block will be accessed before the conditional statement will be evaluated.

● Note: the command block will be accessed at least once!

4/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-02: do(...)

● You can also use a loop that accesses the command block first:

● Here the command block will be accessed before the conditional statement will be evaluated.

Does this make a difference for our example?

4/24

● Note: the command block will be accessed at least once!

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-02: do(...)

● You can also use a loop that accesses the command block first:

● Here the command block will be accessed before the conditional statement will be evaluated.

● Note that the command block will be accessed at least once!

What happens in this example?

5/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-02: do(...)

● You can also use a loop that accesses the command block first:

● Here the command block will be accessed before the conditional statement will be evaluated.

● Note that the command block will be accessed at least once!

This is equivalent to i!=0 (i.e. this asks whether the pointer points to a valid element in memory or not)

What happens in this example?

5/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Endless loops

● Note: if you make a trivially true break statement your loop will run for ever:

This is a trivially fulfilled statement.

6/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Endless loops

If you missed the ++ operator here by incidence you would also create an endless loop.

● Note: if you make a trivially true break statement your loop will run for ever:

7/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Endless loops

If you missed the ++ operator here by incidence you would also create an endless loop.

● Note: if you make a trivially true break statement your loop will run for ever:

7/24

A very popular mistake is a break statement like this:

while(i=0){ … }

Will the loop break in this case?

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Endless loops

● An endless loop can also be intended. Usually you then break it explicitly by the keyword break in the command block.

● Note: if you make a trivially true break statement your loop will run for ever:

8/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Endless loops

● An endless loop can also be intended. Usually you then break it explicitly by the keyword break in the command block.

std::cin is an input stream. It is declared in iostream.h. It expects an input from your keyboard, interprets it as short int and writes it into number.

8/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Endless loops

● An endless loop can also be intended. Usually you then break it explicitly by the keyword break in the command block.

This is a conditional statement that will be discussed in more detail in Lecture­04.

8/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

A question of style

● The given example is perfectly fine, but it is usually not good style to implement it like this: breaking conditions are not clear from the break statement of the loop. This complicates the reading of your code.

9/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

A question of style

This is the better solution: the code is shorter and clearer at the same time.

● The given example is perfectly fine, but it is usually not good style to implement it like this: breaking conditions are not clear from the break statement of the loop. This complicates the reading of your code.

9/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-03: for(...)

● The standard way to iterate something is the for(…) loop:

10/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-03: for(...)

Initializing statement (before loop starts).

● The standard way to iterate something is the for(…) loop:

10/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-03: for(...)

Initializing statement (before loop starts).

Breaking statement.

● The standard way to iterate something is the for(…) loop:

10/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-03: for(...)

Operation that can alter the condition of the break statement.

Initializing statement (before loop starts).

Breaking statement.

● The standard way to iterate something is the for(…) loop:

10/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-03: for(...)

You can have multiple initializations/ operations in for(…).

● The standard way to iterate something is the for(…) loop:

11/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-03: for(...)

You can have multiple initializations/ operations in your for loop.

You can leave statements blank.

12/24

● The standard way to iterate something is the for(…) loop:

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Method-03: for(...)

You can have multiple initializations/ operations in your for loop.

You can leave statements blank.

And of course you can nest all kinds of loop statements.

13/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Range-based for loop

● Another very convenient way to loop standard C++ containers is provided since the formulation of the C++11 standard:

In this example: loop the elements of inputs.

14/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Range-based for loop

● Another very convenient way to loop standard C++ containers is provided since the formulation of the C++11 standard:

Read-only loop.

14/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Range-based for loop

● Another very convenient way to loop standard C++ containers is provided since the formulation of the C++11 standard:

If you want to change the elements of inputs.

14/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Range-based for loop

● Another very convenient way to loop standard C++ containers is provided since the formulation of the C++11 standard:

If you want to change the elements of inputs.

And if you don’t want to care what types should be iterated declare idx as auto.

14/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Keywords: break and continue

● C(++) has several keywords to communicate special cases to the compiler. A few first examples are given in the following. More will occur during the course.

● For all loop statements that we have discussed the keyword break will break the loop. When using continue, the loop will jump to the next iteration (here shown for the for(…) loop).

15/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Keywords: break and continue

● C(++) has several keywords to communicate special cases to the compiler. A few first examples are given in the following. More will occur during the course.

● For all loop statements that we have discussed the keyword break will break the loop. When using continue, the loop will jump to the next iteration (here shown for the for(…) loop).

Note: You may achieve the same result without the use of the keywords. This might also be the cleaner solution.

15/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Variable scopes

● Loop statements are our first example of more than one command block inside a function. The following example has three variable scopes:

16/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Variable scopes

● Loop statements are our first example of more than one command block inside a function. The following example has three variable scopes:

1. Scope

16/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Variable scopes

● Loop statements are our first example of more than one command block inside a function. The following example has three variable scopes:

2. Scope

1. Scope

16/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Variable scopes

● Loop statements are our first example of more than one command block inside a function. The following example has three variable scopes:

3. Scope

1. Scope

2. Scope

16/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Variable scopes

● Loop statements are our first example of more than one command block inside a function. The following example has three variable scopes:

3. Scope

● Each variable is valid just inside the command block it has been declared in.

● As you might have noticed the variable i has been declared twice in this example! The declaration in Scope 2 “shadows” the declaration in Scope 3.

1. Scope

2. Scope

16/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Variable scopes

● Loop statements are our first example of more than one command block inside a function. The following example has three variable scopes:

16/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Global vs. local variables

● A variable inside a command block is often called “local”. The opposite is a variable outside any command block, which is called “global”.

● The local variable will loose its validity once the command block is left. The global variable is accessible everywhere in your TU, or throughout your code.

● In well written/designed C++, usually there is no need for global variables. The difficulty of (esp. mutable) global variables, e.g. in C (or even worse FORTRAN) is, that you never now who altered it and in what way in the course of the program.

16/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Keyword: static

● Loops provide also an occasion to introduce another keyword: static.

static indicates that the variable should be declared only once. It will be initialized with a value by compile time! This happens in the TU before the linking step.

17/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Keyword: static

w/o static

w/o static

static indicates that the variable should be declared only once. It will be initialized with a value by compile time! This happens in the TU before the linking step.

17/24

● Loops provide also an occasion to introduce another keyword: static.

This is how the output of the program looks like

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

w/o static

Keyword: static

w/o static

w/o static

17/24

● Loops provide also an occasion to introduce another keyword: static.

This is how the output of the program looks like

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

w/o static

Keyword: static

w/o static

w/o static

Note: also here a potentially better solution can actually be achieved w/o the keyword.

17/24

● Loops provide also an occasion to introduce another keyword: static.

This is how the output of the program looks like

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Keyword: static

w/o static

Note: when used for functions static means that the function is visible only within its TU (→ turned into executable code at compilation time before(!) linking).

● Loops provide also an occasion to introduce another keyword: static.

18/24

Note: also here a potentially better solution can actually be achieved w/o the keyword.

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

INSTITUTE OF EXPERIMENTAL PARTICLE PHYSICS (IEKP) – PHYSICS FACULTY

Part 2:

Container classes

19/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

C++ container classes

● The standard use case for a loop is the iteration of a set of similar elements. C++ provides high performance container classes to hold objects, with varying level of complexity for certain functionalities. E.g.:

● std::array<T> – C++ equivalent to C array, fixed length

● std::vector<T> – dynamically expandable

● std::list<T> – constant time insert/erase operations

● std::stack<T> – FILO adaptation of upper containers

● std::queue<T> – FIFO adaptation of upper containers

● std::set<S, T> – associative array (unique elements only)

● std::map<S, T> – associative array (same elem’s possible)

● A container class is a holder object that stores a collection of other objects.

● All container classes are implemented as class templates (→ see Lecture­08), i.e. whether a std::vector holds int or float (or even a user-defined object) is determined by “argument” during of object declaration.

20/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

std::vector<T>

● Saves T (T=int, float, …) in normal sequences, can be extended dynamically.

20/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

std::vector<T>

Declaration and initialization w/ <int>

● Saves T (T=int, float, …) in normal sequences, can be extended dynamically.

20/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

std::vector<T>

Declaration and initialization w/ <int>

Add nextValue to end

● Saves T (T=int, float, …) in normal sequences, can be extended dynamically.

20/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

std::vector<T>

Declaration and initialization w/ <int>

Add nextValue to end

Determine size & access elements

● Saves T (T=int, float, …) in normal sequences, can be extended dynamically.

20/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

std::vector<T>

Declaration and initialization w/ <int>

Add nextValue to end

A better way to iterate C++ containers

● Saves T (T=int, float, …) in normal sequences, can be extended dynamically.

20/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Iterators

● An iterator is an object that serves for the access to other objects in a given ensemble. Such an ensemble can be a C++ container object.

● They must fulfill certain criteria, e.g. provide member functions/operators like e.g. ++•, *•, … 

● Five classes of iterators are defined in the C++ standards (=grammar book):

Input

Output

Forward Bidirectional Random Access

21/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Iterators

● An iterator is an object that serves for the access to other objects in a given ensemble. Such an ensemble can be a C++ container object.

● The simplest iterator is the built-in pointer.

● They must fulfill certain criteria, e.g. provide member functions/operators like e.g. ++•, *•, … 

● Five classes of iterators are defined in the C++ standards (=grammar book):

Input

Output

Forward Bidirectional Random Access

21/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Iterators

● An iterator is an object that serves for the access to other objects in a given ensemble. Such an ensemble can be a C++ container object.

● The simplest iterator is the built-in pointer.

● They must fulfill certain criteria, e.g. provide member functions/operators like e.g. ++•, *•, … 

● Five classes of iterators are defined in the C++ standards (=grammar book):

Input

● The C++ standard containers have several iterators as data members that can be accessed by member functions like begin(), end() and rbegin(), rend(), …

Output

Forward Bidirectional Random Access

21/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

● Saves S and T as a key-value pair. At the time of insertion key is already sorted. For this purpose std::map requires a definition of the “<” operator for key.

std::map<S, T>22/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

std::map<S, T>

Our map associates a word with another word

● Saves S and T as a key-value pair. At the time of insertion key is already sorted. For this purpose std::map requires a definition of the “<” operator for key.

22/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Our map associates a word with another word

Get the value for a given key.

std::map<S, T>

● Saves S and T as a key-value pair. At the time of insertion key is already sorted. For this purpose std::map requires a definition of the “<” operator for key.

22/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Our map associates a word with another word

Get the value for a given key.

Check if a key exists.

std::map<S, T>

● Saves S and T as a key-value pair. At the time of insertion key is already sorted. For this purpose std::map requires a definition of the “<” operator for key.

22/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Our map associates a word with another word

Get the value for a given key.

Check if a key exists. Iterator that points to the end of dict.

std::map<S, T>

● Saves S and T as a key-value pair. At the time of insertion key is already sorted. For this purpose std::map requires a definition of the “<” operator for key.

22/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Our map associates a word with another word

Get the value for a given key.

Check if a key exists. Iterator that points to the end of dict.

Assign a value to a given key.

std::map<S, T>

● Saves S and T as a key-value pair. At the time of insertion key is already sorted. For this purpose std::map requires a definition of the “<” operator for key.

22/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Our map associates a word with another word

Get the value for a given key.

Check if a key exists. Iterator that points to the end of dict.

Assign a value to a given key.

std::map<S, T>

How you could use these two functions…

Note: you can learn much more about std::map in one of the next exercises.

● Saves S and T as a key-value pair. At the time of insertion key is already sorted. For this purpose std::map requires a definition of the “<” operator for key.

23/24

Priv. Doz. Dr. Roger Wolf http://ekpwww.physik.uni­karlsruhe.de/~rwolf/

Summary

● The while(...), do(...), for(…) loop.

● Endless loops.

● First key words break and continue.

● Variable scopes.

● The key word static.

● C++ containers: std::vector<T> and std::map<S,T>.

24/24

top related