0% found this document useful (0 votes)
10 views70 pages

Lecture1 Petrov

Uploaded by

hasan zahid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views70 pages

Lecture1 Petrov

Uploaded by

hasan zahid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Computer simulations of

telecommunication networks;

C++ introduction

Dmitry Petrov, PhD


[email protected]
Agenda

 Network Modeling and Simulations


 About Magister Solutions
 When an why to use simulations?
 Selected models and examples

 C++ introduction
 Basics of C++ programming
 Running C++ programs and examples
 Main concepts
 Useful materials and home work

© 2015 Magister Solutions Ltd


Network Modeling and Simulations
Magister Solutions – Quick facts
Quick Facts
Resources ~30 employees within main company, incl. 2 professors, 12 doctors and 8
Ph.D. students. Roughly 40 employees when including subsidiaries.

Services R&D, simulators and test-beds, training and advisory and software
services. Main focus on telecommunication technologies

Technology Wireless communication technologies, incl. UMTS (3G), HSPA and HSPA+
competence (3.5/3.75G), LTE, LTE-A and WiMAX (3.9G/4G), Wi-Fi, cognitive networks,
DVB-RCS, DVB-S2, positioning systems (GPS)

R&D tool expertise System designing; simulator development (C/C++) and maintenance;
simulations; KPI analysis tool development (Perl, Matlab, C/C++); network
and device KPI analysis

Publications Over 110 international scientific publications

Patents Co-authoring in over 20 patents covering WCDMA, HSPA, LTE, LTE-A

© 2015 Magister Solutions Ltd


Magister Solutions

Mobile, satellite and security technologies

© 2015 Magister Solutions Ltd


Simulators and test-beds

© 2015 Magister Solutions Ltd


Simulators and test-beds – Own tools

NS-3 with additional


modules for LTE,
wireless mesh and
satellite
communication

© 2015 Magister Solutions Ltd


What is a model?

 Modeling is a process of producing a model


 A model is a representation of the construction and
working of some system of interest
 A model is similar to but simpler than the system it
represents
 Close approximation to the real system and incorporate
most of its salient features
 Judicious tradeoff between realism and simplicity

© 2015 Magister Solutions Ltd


What is a simulation?

 Simulation of a system is the operation of a model to the


system
 Model can be reconfigured and experimented with
 Usually this is impractical to do in the system it represents
 Simulation is a tool
 to evaluate the performance of a system, existing or proposed,
under different configurations of interest and over long periods
of real time

© 2015 Magister Solutions Ltd


“Essentially, all models are wrong, but
some are useful”

[George E. P. Box and Norman R. Draper. Empirical


Model-Building and Response Surfaces. Wiley, 1987]
Applications of simulations
 Analysis of air pollutant dispersion using atmospheric dispersion modeling
 Design of complex systems such as aircraft and also logistics systems
 Design of Noise barriers to effect roadway noise mitigation
 Flight simulators to train pilots
 Weather forecasting
 Simulation of other computers is emulation.
 Forecasting of prices on financial markets
 Behavior of structures (such as buildings and industrial parts) under stress and other conditions
 Design of industrial processes, such as chemical processing plants
 Strategic Management and Organizational Studies
 Reservoir simulation for the petroleum engineering to model the subsurface reservoir
 Process Engineering Simulation tools.
 Robot simulators for the design of robots and robot control algorithms
 Urban Simulation Models that simulate dynamic patterns of urban development and responses
to urban land use and transportation policies
 Traffic engineering to plan or redesign parts of the street network from single junctions over
cities to a national highway network, for transportation system planning, design and operations
 Modeling car crashes to test safety mechanisms in new vehicle models

© 2015 Magister Solutions Ltd


How may networks be studied?

 Measurements from real deivces / networks


 Protocol analysers and monitors
 Drive test with specialized erquipment
 Measurements from real devices
 $ and time consuming, new devices not always avaliable
 Test networks / emulation
 Access to all equipment / software
 Open-sourse software
 Expencive and not large enough
 Mathematical analysis
 Matlab, pen’n’paper
 Too many simplifications in complex dynamc systems

© 2015 Magister Solutions Ltd


Why to simulate?
 Develop and test vast amount of potential solutions for current
and future challenges without excessive costs

 Wireless
 Reproducibility
 Fidelity (especially, real-time constraints)
 Radios may not exist or be available
 Field tests in realistic conditions cost $$
 Scenarios with desired parameters

 Scalability
 10,000+ nodes?
 For smaller configurations, execution time

© 2015 Magister Solutions Ltd


When to simulate

 When the analytical model/solution is not possible or


feasible.
 Many times, simulation results are used to verify
analytical solutions in order to make sure that the
system is modeled correctly using analytical approaches.
 Dynamic systems, which involve randomness and change
of state with time.
 Complex dynamic systems, which are so complex that
when analyzed theoretically will require too many
simplifications. In such cases, it is not possible to study the
system and analyze it analytically.

© 2015 Magister Solutions Ltd


New technology path
R&D Analytical
Concept
model

Test
Simulations
network

Commerci
alization
Explotation

Planning Commitment Optimization

© 2015 Magister Solutions Ltd


Simulation workflow
Simulation model Simulation Simulation analysis
experiment
Identify the problem
Select appropriate Interpret and present
experimental design results
Formulate the problem
Establish experimental Recommend further
condition for runs course of action
Collect and process
real world data
Perform simulation
runs
Formulate and develop
a model

Validate the model


 parameter tuning
 simulation scenario tuning
 model debugging

© 2015 Magister Solutions Ltd


What can be achieved with
simulations?
 Test new and advanced features and their gains
 Study wide range of scenarios
 Identify bottlenecks in processes
 Prevent under or over-utilisation of resources
 Safe and chaper way to evaluate the side effects
 Optimize the performance of the system
 Balance expences and improvements in user experience

© 2015 Magister Solutions Ltd


Revolutionary applications in mobile
industry
1. Need for unlimited telephony
1. Paradigm shift: personalization of communications
2. Two-way paging
3. Internet browsing (WiFi)
4. Merge laptop function for a mobile use
5. New paradigm shift:
“Instead of consumer going to the Internet, the Internet
will come to them”*
1. Thirst for data will continue
2. Form and context of communications
3. Clever content discovery
4. M2M and MTC + steering

* “5G: Personal Mobile Internet beyond What Cellular Did to Telephony”


by G. Fettweis and S. Alamouti, IEEE communication mag., Feb. 2014.
© 2015 Magister Solutions Ltd
Simulator types

 Different ways of dividing simulators


 Running principle: discrete event, continuous, …
 Level of detail: static, quasi-static, dynamic, …
 Modeling purpose: wireless radio access, wired, …
 Confidentiality: proprietary, open

© 2015 Magister Solutions Ltd


Simulators and Network Planning Tools

 NPTs:  Simulators:
 Focus on radio part:  Representation of a real
 propagation and system
interference models  Both Radio and Core
 Real maps planes (end2end)
 Radio planning and  Detailed realization of
optimization protocols and features
 Some posses simulation  Statistics for specific
possibilities: UE, eNB, link
 Traffic modeling  RB or even symbol
resolution on PHY
 Packet tracing

© 2015 Magister Solutions Ltd


Simulator types

 Emulation: The process of designing and building hardware or firmware


(i.e., prototype) that imitates the functionality of the real system.
 Monte Carlo simulation: Any simulation that has no time axis. Monte
Carlo simulation is used to model probabilistic phenomena that do not
change with time, or to evaluate non-probabilistic expressions using
probabilistic techniques.
 Trace-driven simulation: Any simulation that uses an ordered list of
real-world events as input.
 Continuous-event simulation: In some systems, the state changes
occur all the time, not merely at discrete times.
 Discrete-event simulation: A discrete-event simulation is characterized
by two features: (1) within any interval of time, one can find a subinterval
in which no event occurs and no state variables change; (2) the number of
events is finite

© 2015 Magister Solutions Ltd


Static vs. dynamic simulators
System simulators
Static simulators Quasi-Static Dynamic
“Snapshot” simulators simulators
Simplified and limited
Algorithms algorithms, e.g no outer Extensively modelled Fully modelled RRM
power control RRM
Varied every timeslot
Path Loss Fixed Fixed
(slot, TTI, etc.)

Time Domain No Yes Yes

Mobility Static Static Moving randomly

Computational
Fast Middle Slow
Complexity
Interference study between RRM study excluding Mobility Study, RRM
USE Cases systems, etc. mobility, etc. Study, etc.

© 2015 Magister Solutions Ltd


Link and System level simulations

 Link Level:
 1 UE – 1eNB connection is simulated
 1 subcarrier / 1 time slot resolution
 Mainly physical layer procedures:
coding, modulation, complicated channel models, channel
estimation etc.
 Provides input for system level simulations
 Actual data transmission
 System Level:
 Hundreds of UEs - tens of eNBs
 Resource Block (RB) resolution and more simple channel models
(pathloss + shadowing + fast fading)
 Includes full protocol stack and many other procedures
 TBER is defined by BLER-SINR curves form Link level
 Simulation of received SINRs

© 2015 Magister Solutions Ltd


Link and system level simulators

© 2015 Magister Solutions Ltd


Simulator input, i.e. parameterization

 Basically everything within a simulation may/need to be


parameterized
 Number of terminals
 Simulation length
 Scenario and topology
 Mobility
 Traffic
 RRM specifics
 …

© 2015 Magister Solutions Ltd


Simulation scenarios

 Simulation scenarios are


often standardized by
standardization
organizations for specific
purposes, e.g.
 Results verification
 Problem validation

Macro 57 with wrap around

© 2015 Magister Solutions Ltd


Simulation scenarios (cont.)
[3GPP TR 36.839]

100 m

UE was placed
randomly on the
circle and it takes a
random drive
direction towards
the pico

[T. Nihtilä, "Capacity Improvement by Employing


Femto Cells in a Macro Cell HSDPA Network", Proc. of
the IEEE Symposium on Computers and
Communications, Marrakech, Marocco, July 6-9,
2008]

© 2015 Magister Solutions Ltd


Simulation scenarios (cont.)

 Springwald
 ISD varies being about
500m in minimum and
about 1500m in maximum
 Realism
 Varying load per BS
 Mobility problems,
coverage holes
 UL / DL imbalance issues

[J. Turkka and A. Lobinger, “Non-regular Layout for


Cellular Network System Simulations”, Proc. of the 21st
Annual IEEE International Symposium on Personal,
Indoor and Mobile Radio Communications, Istanbul,
Turkey, September 26-29, 2010]

© 2015 Magister Solutions Ltd


Signal propagation, fading types

 Radio propagation
 Empirical mathematical formulation for the characterization of
radio wave propagation as a function of frequency,
distance and other conditions

 In practice, most simulation studies use empirical models


that have been developed based on measurements taken in
various real environments
 Hata model
 COST 231 extension to Hata model
 COST 231 Walfish-Ikegami model

© 2015 Magister Solutions Ltd


Fading types (cont.)

 Slow fading
 Shadow fading is caused by obstacles in the propagation path
between the UE and the eNodeB and can be interpreted as the
irregularities of the geographical characteristics of the terrain
introduced with respect to the average pathloss obtained from the
macroscopic pathloss model
 Some part of the transmitted signal is lost through absorption,
reflection, scattering, and diffraction
 Fast fading
 Fast fading occurs if the channel impulse response changes rapidly
within the symbol duration
 Fast fading occurs when the coherence time of the channel is
smaller than the symbol period of the transmitted signal
 This causes frequency dispersion or time selective fading due to
Doppler spreading
 Fast Fading is due to reflections of local objects and the motion of
the objects relative to those objects

© 2015 Magister Solutions Ltd


Propagation, slow and fast fading

© 2015 Magister Solutions Ltd


Propagation map with slow fading Dominance map

© 2015 Magister Solutions Ltd


Traffic models

 Defined by standardization packet call packet call

organizations Nd

 Infinite buffer Dpc


(Reading Time)

 FTP main object


embedded objects
 Constant Bit Rate (CBR)
 HTTP models (bursty)
Packet calls
 AMR codecs for VoIP

Dpc

Packets of file 1 Packets of file 2 Packets of file 3

© 2015 Magister Solutions Ltd


Mobility models

 Mobility models represent the movement of mobile users, and


how their location, velocity and acceleration change over time
 In certain scenarios the mobility plays an important role, e.g.
mobile ad hoc networks
 Several ways of categorizing mobility models
 Traces and synthetic mobility models
 Entity and group mobility models
 Human, animal and vehicle mobility models
 Normal situation and special situation mobility models
 Usual factors
 Speed: [speedmin; speedmax]
 Direction: [0, pi]
 Time or distance before making the next turn

© 2015 Magister Solutions Ltd


Mobility models

Random walk Random waypoint

© 2015 Magister Solutions Ltd


New features in existing networks
Carrier Aggregation Multipoint Tx
DC capable
UE

Spectrum 1 Spectrum 2

5 MHz

PA3 Channel (Softer Handover Users)


50

45

Mean Softer HO User BR Gain (%)


40

35

30

25

20

15

10

0
0 5 10 15 20 25 30 35
Users per cell

© 2015 Magister Solutions Ltd


Converged Infrastructure for Emerging
Regions (CIER) challenges
 Limitations to OPEX and
CAPEX due to limited
financial capabilities
 Lack of wired infrastructures
 Huge distances between
localities
 Lack of reliable energy supply
 Lack of well-trained service
personnel
 Sparsely populated areas
 Challenging socioeconomic
and political conditions

© 2015 Magister Solutions Ltd


Simulation scenario
TestBed
Sink
integration

Mesh node

© 2015 Magister Solutions Ltd


Real-time demo Play/TX video

Display

Display NEF player

Computer Tap IF
Sensors
NS3 Simulator
Tap dev.
Edge

Gateway
Mesh + side load

Edge Emu dev.

Wire/Wired?
Display

RX/Play video

© 2015 Magister Solutions Ltd


Enhanced Multicarrier Techniques for Professional
Ad-Hoc and Cell-Based Communications

 Main objectives of EMPHATIC:


 Enhanced multicarrier techniques (FB-MC)
 Flexible radio platform, based on variable FB processing
 Co-existence of radio frequency bands together with
Professional Mobile Radio (PMR)

© 2015 Magister Solutions Ltd


COgnitive network ManageMent under
UNcErtainty (COMMUNE) project

© 2015 Magister Solutions Ltd


Results of Cognitive Self-Healing in
LTE
Coverage hole is significantly
Problematic region (cell 29) reduced after compensation

© 2015 Magister Solutions Ltd


NEF player, Demo
Simulators and
test-beds

GUI
1
NEF-
library

GUI
Matlab
2
2. Easy integrate and take into use
Optimized C++ based NEF-library can be
GUI easily integrated with different simulators.
... Simulations can be visualized with QT
n
based NEF-Player in Windows and Linux
environments NEF Player

1. Savings in development and maintenance 3. Faster results analysis and development cycle
No need to develop or maintain separate graphical Efficient simulation visualization helps the analyze
user interfaces (GUI) or visualization tools for system / network performance for R&D and marketing
different simulators purposes for both technical and non-technical
audience

See demo at: http://youtu.be/LlPUHyXHszo

© 2015 Magister Solutions Ltd


C++ introduction
Programming languages*
 Procedural (C, Fortran, Pascal, Basic)
 expresses the procedure to be followed to solve a problem
 Functional and Logical (Lisp, Scheme, Haskell)
 the primary focus is on the return values of functions, and side effects and other
means storing state are strongly discouraged.
 allow the computer to reason about the consequences of statements declared by
programmer
 Object-oriented (C++, C#, Java)
 the world is a collection of objects that have internal data and external means of
accessing parts of that data.
 Scripting (Perl, PHP, Python)
 often procedural and may contain elements of object-oriented languages, but
are typically not meant to be full-fledged programming languages (no var.
declaration, no compile-time type checking, etc.)

* A programming language is a formal constructed language designed to communicate


instructions to a machine, particularly a computer. Programming languages can be used to
create programs to control the behavior of a machine or to express algorithms.

© 2015 Magister Solutions Ltd


C++ history
 C language was developed in 1972 by Dennis Ritchie at Bell Telephone
laboratories, primarily as a systems programming language.
 In 1973, Ritchie and Ken Thompson rewrote most of the UNIX operating
system using C.
 In 1983, the American National Standards Institute (ANSI) formed a
committee to establish a formal standard for C.
 In 1990 the International Organization for Standardization adopted ANSI C
(with a few minor modifications). This version of C became known as C90.
 In 1999, the ANSI committee released a new version - C99.
It adopted many features which had already made their way into compilers as extensions, or had
been implemented in C++.
 C++ was developed by Bjarne Stroustrup at Bell Labs as an extension
to C, starting in 1979. C++ was ratified in 1998 by the ISO committee,
and again in 2003 (called C++03)
 A new version of the standard, known as C++11 has been made available

© 2015 Magister Solutions Ltd


Processing a C++ program

C++ program

Editor

Preprocessor Preprocessor directives begin with #

Compiler Translation into machine language (object program);


checks the rules of language.
Library
Combination with other programs
Linker
provided by the SDK -> executable
Load into main memory
Loader

Execution

© 2015 Magister Solutions Ltd


Basics of a C++ Program

 Syntax - rules specify which statements (instructions) are legal.


 Function is a group of code statements which are given a name
 Variable is a portion of memory to store a value.
 Each variable needs a name that identifies it and distinguishes it from the
others.
 Program needs to be aware of data type stored in the variable.
 Constants are expressions with a fixed value.
 We can begin to operate with variables and constants by using operators.
 Namespaces subdivide the global scope into distinct, named scopes, and
so are useful for preventing name collisions in the global scope.
 In general, every .cc (.cc, .cpp, .CPP, .c++, .cp, or .cxx) file should have
an associated header .h (.hh) file. Order of inclusion:
 dir2/foo2.h.
 C and C++ system files.
 Other libraries' .h files.
 Your project's .h files.

© 2015 Magister Solutions Ltd


Source -> program
// my first program in C++
#include <iostream>
using namespace std;

int main()
{
cout << "My first C++ program." << endl;
return 0;
}

 Install Ubuntu modules:


 sudo apt-get install build-essential g++
 Compile:
 gcc -o test1 test1.cc -lstdc++
 g++ -o main -I /source/includes main.cpp
// -I option to specify an alternate include directory
 Run
 ./test1

© 2015 Magister Solutions Ltd


C++ IDEs

 Text editor (gedit, notepad++, etc.)


 Online code execution:
http://www.tutorialspoint.com/compile_cpp_online.php
 QT: http://qt-project.org/
 Eclipse CDT (C/C++ Development Tooling):
https://eclipse.org/cdt/
 Microsoft Visual Studio:
https://msdn.microsoft.com/en-us/vstudio/hh386302.aspx
 Emacs: http://www.gnu.org/software/emacs/

© 2015 Magister Solutions Ltd


Data types

 Data types – set of values together with a set of operations

C++’s Data Types

Simple Pointers
Structured
Integral: char, short, struct product {
int weight;
int, bool, long, unsigned… double price;
} ;
Floating point: float, double, …
product apple;
product banana, melon;
Enumeration: enum Color { RED, GREEN, BLUE }; apple.weight = 50;
Color r = RED; apple.price = 0.20;

© 2015 Magister Solutions Ltd


Initialization and static casting
#include <iostream>
#include <string>
using namespace std;

int main ()
{
int a=5; // initial value: 5
int b(3); // initial value: 3
int c{2}; // initial value: 2 C++11
int result; // initial value undetermined

a = a + b;
result = a - c;
cout << result;

string mystring;
mystring = "This is the initial string content";
cout << mystring << endl;

/* magical function returns the age in years */


int age = getAge();
/* magical function returns the number of visits */
int pain_visits = getVisits();

float visits_per_year = pain_visits / age;


// float visits_per_year = pain_visits / static_cast<float>(age); // float(age);

return 0;
}

© 2015 Magister Solutions Ltd


If … else statements in C++
#include <iostream>

using namespace std;

int main() // Most important part of the program!


{
int age; // Need a variable...

cout<<"Please input your age: "; // Asks for age


cin>> age; // The input is put in age
cin.ignore(); // Throw away enter
if ( age < 100 ) { // If the age is less than 100
cout<<"You are pretty young!\n"; // Just to show you it works...
}
else if ( age == 100 ) { // I use else just to show an example
cout<<"You are old\n"; // Just to show you it works...
}
else {
cout<<"You are really old\n"; // Executed if no other statement is
}
cin.get();
}

Boolean operations: !( 1 || 0 ); !( 1 || 1 && 0 ); !( ( 1 || 0 ) && 0 );

© 2015 Magister Solutions Ltd


Loops

// continue loop example


#include <iostream>
using namespace std;

int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "liftoff!\n";
}

Other statements: while (n>0) {… }


switch (x) { case 1: … default: … }

© 2015 Magister Solutions Ltd


An array is a series of elements of the same type placed in
contiguous memory locations that can be individually
referenced by adding an index to a unique identifier.
// arrays as parameters
#include <iostream>
using namespace std;

void printarray (int arg[], int length) {


for (int n=0; n<length; ++n)
cout << arg[n] << “ “;
cout << “\n”;
}

int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 1; Other examples:
} • char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
• char myword[] = "Hello";
• int jimmy [3][5]; // 2D array
• array<int,3> myarray {10,20,30}; //#include <array>

© 2015 Magister Solutions Ltd


Pointers

 Variables - locations in the computer's memory which can


be accessed by their identifier (their name).
 Address-of operator: foo = &myvar;
 Dereference operator: bar = *foo;
 Declaring pointers:
double * decimals;

const char * foo = "hello";

© 2015 Magister Solutions Ltd


Pointers example
#include <iostream>
using namespace std;

int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue; // p1 = address of firstvalue


p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed to by p1 = 10
*p2 = *p1; // value pointed to by p2 = value pointed by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20

cout << "firstvalue is " << firstvalue << '\n';


cout << "secondvalue is " << secondvalue << '\n';
return 0;
}

What values will be in firstvalue and in secondvalue?

© 2015 Magister Solutions Ltd


Constants are expressions with a
fixed value.
Const values: Pointer to constant data:
#include <iostream>
void print_all (const int* start, const int*
using namespace std;
stop)
{
const double pi = 3.14159;
const int * current = start;
const char newline = '\n';
while (current != stop) {
cout << *current << '\n';
int main ()
++current; // increment pointer
{
}
double r=5.0; // radius
}
double circle;

circle = 2 * pi * r;
cout << circle;
cout << newline;
} Question:
int x;
int * const p_int = &x;

© 2015 Magister Solutions Ltd


Class is an element of expanded concept of data structures:
like data structures, they can contain data members, but they can also
contain functions as members (methods).
Contractors:
// classes example
#include <iostream> using namespace std; Rectangle::Rectangle () {
width = 5;
class Rectangle { height = 5;
private: }
int width, height;
public:
void set_values (int,int); Rectangle::Rectangle (int a, int b) {
int area() {return width*height;} width = a;
}; height = b;
}
void Rectangle::set_values (int x, int y) {
width = x;
height = y; Rectangle rect (3,4);
} Rectangle rectb;

int main () {
Rectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
Pointers:
return 0; Rectangle obj (3, 4);
} Rectangle * foo, * bar;
foo = &obj;
bar = new Rectangle (5, 6);
cout << "*bar's area: " << bar->area() << '\n';
© 2015 Magister Solutions Ltd
#include <iostream>

Inheritance,
using namespace std;

class Polygon {

polymorphism
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b;}
};

class Rectangle: public Polygon {


public:
int area ()
{ return width * height; }
};

class Triangle: public Polygon {


public:
int area ()
{ return width * height / 2; }
};

int main () {
Rectangle rect;
Triangle trgl;
Polygon * ppoly1 = &rect;
Polygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << rect.area() << '\n';
cout << trgl.area() << '\n';
return 0;
}

© 2015 Magister Solutions Ltd


Class templates
// class templates
#include <iostream>
using namespace std;

template <class T>


class mypair {
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
T getmax ();
};

template <class T>


T mypair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}

int main () {
mypair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}

© 2015 Magister Solutions Ltd


Dynamic casting
#include <iostream>

using namespace std;

class Base { virtual void dummy() {} };


class Derived: public Base { int a; };

int main()
{
Base * pba = new Derived;
Base * pbb = new Base;
Derived * pd;

pd = dynamic_cast<Derived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast.\n";

pd = dynamic_cast<Derived*>(pbb); What will be returned?


if (pd==0) cout << "Null pointer on second type-cast.\n";

return 0;
}

© 2015 Magister Solutions Ltd


Pointers to functions
- passing a function as an argument to another
function. #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,n;
int (*minus)(int,int) = subtraction;

m = operation (7, 5, addition);


n = operation (20, m, minus);
cout <<n;
return 0;
}

© 2015 Magister Solutions Ltd


C++11 features

 Automatic type definition: int x = 3; auto itr = address_book.begin();


auto y = x;

 Ranged for loops: vector<int> vec;


vec.push_back( 10 );
vec.push_back( 20 );

for (int &i : vec )


{
cout << i;
}
 Lambda functions
 Performance improvements
 The new C++ memory model and the feature it supports:
multithreading, etc…
 $ g++ -std=c++11 your_file.cpp -o your_program

© 2015 Magister Solutions Ltd


Useful links and books
 http://www.cplusplus.com/
 http://en.cppreference.com
 http://www.learncpp.com/
 http://www.cprogramming.com/tutorial.html

 https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html

 Accelerated C++: Practical Programming by Example,


Andrew Koenig & Barbara E. Moo, 2000
 C++ Primer, 5th Edition, Stanley B. Lippman & Josée Lajoie
& Barbara E. Moo, 2012
 The C++ Programming Language, 4th Edition, Bjarne
Stroustrup, May 2013

© 2015 Magister Solutions Ltd


Home work
Write a simple histogram class, called Histogram, which collects samples into bins of
equal width. For this exercise, the histogram is defined by a lower (L) and upper (H)
boundary and bin width (W). The interval of numbers, on which the histogram operates,
is half open:
[L; H[
i.e. the upper boundary is not included. Similarly for bins:
the first bin collects samples in the interval [L; L+W[,
the second bin collects from interval [L+W; L+2W[,
... etc.
The last bin collects from interval [H-W, H[. (See the figure)
If the difference between the upper and lower boundary H - L is not multiple of bin width
W, increase the upper boundary H so, that (H-L) is fully divisible by W. In addition to
that, the histogram collects number of samples below the lower boundary (<L) and
above or equal to the upper boundary (>=H).

© 2015 Magister Solutions Ltd


Home work(cont.)
 Write the following operations:
 constructor with low, high boundaries and optional bin width. If the bin width is
not given, assume it is 1.
 copy constructor
 assignment operator
 destructor - if needed, depends on your implementation
 function for adding a new sample into the histogram (A)
 function returning the total number of samples (T)
 function returning the number of samples below the lower bound (B)
 function returning the number of samples above the upper bound (V)
 function returning the average of all samples in the histogram - including those
below and above (M)
 function returning true, if there are no samples in the histogram
 function for clearing all values
 function returning the number of bins - for testing
 function returning the number of samples in certain bin - for testing
 operator << for writing the histogram out to a stream (must work with
std::ostream). For each bin, write the following on one line:
bin lower boundary TAB number of samples in that bin TAB cumulative number
of samples up to and including this bin.
Write also one line for samples below and above the histogram’s interval. See
the output below for an example.

© 2015 Magister Solutions Ltd


Home work(cont.)

 Organize your code in the following way:


 Makefile OR compile.sh - the make file or shell script shall
compile, link and start your program. If you use the online
compiler, you don't need to write this file.
 histogram.h - header file with class declaration
 histogram.cc - implementation file with function definitions
 main.cc - main file, which will contain the following code:

Select appropriate names for all functions. All samples will have type double.
Assume there will be no NaNs or infinite samples. Use standard C++, you can
use STL if you want. No other library is permitted. Your code must compile with
GNU g++ 4.1.x or higher (you need at least 4.7.x if you use C++11).

© 2015 Magister Solutions Ltd


Home work (main.cc code)
Expected output:
#include <iostream> Total samples: 5, below: 1, above: 2, mean:
#include "histogram.h" 6.4
below 1 1
int main() 1 0 1
{ 2 1 2
Histogram h(1, 7, 1) 3 0 2
Histogram g = h; 4 0 2
h.A(20); 5 1 3
h.A(10); 6 0 3
h.A(2); above 2 5
h.A(5);
h.A(-5);
g = h;
std::cout << "Total samples: " << h.T() <<
", below: " << h.B()
<< ", above: " << h.V() << ",
mean: " << h.M() << std::endl;
std::cout << g << std::endl;
! substitute the proper names of
return 0;
your functions for the letters !
}

© 2015 Magister Solutions Ltd


Thank you for attention!

Thanks to my colleagues:
Jani Puttonen, Petri Eskelinen, Anotoine Trux, Fedor
Chernogorov, Janne Kurjenniemi, Timo Hämäläinen
and others as well!

Dmitry Petrov,
[email protected]

© 2015 Magister Solutions Ltd

You might also like