C++ Slides
C++ Slides
Nicholas Tan
nicholas.tan12@imperial.ac.uk
Imperial College Software Society and Robotics Society
February 7, 2014
1 / 95
2 / 95
Contents I
0. Introduction
What is C++?
Why C++?
What You Will Need
The Compiler
Compiling and Running
1. A Tutorial Introduction
Getting Started
Variables and Arithmetic Expressions
For Loops
If Statements
Constants
Input and Output
Arrays
Functions
Passing Arguments by Reference
3 / 95
Contents II
Contents III
5 / 95
0. Introduction
0. Introduction
6 / 95
You define a sequence of commands that are run one after the
next, allowing you to change the state of the computer.
BCPL
7 / 95
C++ is:
General purpose
Fast
Portable
Widely used
It has many libraries and pre-made functions that allow you to
8 / 95
For Windows:
For the text editor Notepad++ , and the g++ compiler can be installed
from MinGW , which can be downloaded here . When installing tick
the base, g++ and msys boxes. Make a shortcut to the
C:\MinGW\msys\1.0\msys.bat (MinGW Shell) script. Run the
bat script then run the
echo 'export PATH=$PATH:/c/MinGW/bin'>> .profile
For Mac OS X:
Xcode comes with both g++ and a text editor. Xcode can be
downloaded from the App Store, then install Command Line Tools
from Preferences\Downloads.
9 / 95
This turns your code into machine code, but also stores the
names of functions you need from other files needed.
Linking
This gets the functions you need from other files and inserts
them into the object code, and makes the file a proper
executable.
touch makes a new file, if it does not exist. If the file does
exist it updates the timestamp.
start filename.cpp
or open filename.cpp
start (on Windows) or open (on Mac) will open the file for
you to write the code in.
g++ filename.cpp
or ./a.out
This will run the program that was just compiled to a.exe
(Windows) or a.out (Mac / Linux).
11 / 95
Tips
Command History
You can go through your previous commands, by using the up &
down arrow keys.
Autocompletion
File names and directory names can be completed using the tab key.
This saves you from typing out long filenames, e.g. say you wanted to
compile the file verylongfilename.cpp you could type g++ ver
then press the tab key. If the file/directory name is ambiguous it will
complete up to that point, then list the files.
Chaining Commands Together
Commands can be chained together using &&. If the first command
completes successfully (i.e. returns 0), then the next command will
be run. If you do not care whether it was successful, you can use ;
instead. For example, say you want to compile the file hi.cpp then
run it, you can use g++ hi.cpp && ./a.out. That way, if the
compilation fails, the program will not be run.
12 / 95
The -Wall & -Wextra turns on all warnings (for things that
are bad) and extra warnings (for things the compiler thinks you
may make a mistake doing it that way). These are useful for
helping you debug your code.
g++ codetocompile.cpp -o outputfilename The -o flag
for g++ allows you to change the output file name from the
default (a.out) to outputfilename.
13 / 95
pwd
pwd tells you your present working directory, i.e. were you
currently are in the filesystem.
./a.out > filename
14 / 95
1. A Tutorial Introduction
1. A Tutorial Introduction
15 / 95
HelloWorld.cpp
16 / 95
This tells the compiler that we will be using things from the
input output stream standard library, namely cout ans endl.
using namespace std;
17 / 95
18 / 95
19 / 95
Semicolons Everywhere;
20 / 95
More
1
2
3
4
5
6
7
8
9
10
11
12
couting
#include <iostream>
using namespace std;
int main()
{
cout << "Hello " // no ; so is continued to the next line
<< "World"
<< endl << endl; // outputs: Hello World
13
14
15
16
17
18
19 }
Morecouting.cpp
21 / 95
Description
Examples
true, false
0, 10, -100
Variable Declaration
Type Name;
Type Name = Value;
22 / 95
Arithmetic Operators
C
++
can do arithmetic:
Syntax
Name
a = b
Assignment Operator
int x = 3
Addition
x + 7
Subtraction
5 - 4
Multiplication
6*3
Division
2/3, 2.0/3.0
Modulo (integer remainder) 5 % 3
Prefix increment
++x
Postfix increment
x++
Prefix decrement
--x
Postfix decrement
x--
a + b
a - b
a * b
a / b
a % b
++a
a++
--a
a--
23 / 95
If two integers are divided, the result will be the solution rounded
down, i.e. 3/2 is 1, 2/3 is 0.
=
=
is not
==
24 / 95
#include <iostream>
using namespace std;
/* Kelvin - Fahrenheit table
for fahr = 0, 15, ..., 120*/
int main () {
int min = 0, max = 120, step = 15;
int fahr = min;
13
14
15
16
17 }
FahrtoKel.cpp
Conversion Equation:
kel =
5 (fahr 32)
+273
9
Programs Output:
F
K
0
255
15
263
30
271
45
280
60
288
75
296
90
305
105
313
120
321
25 / 95
While Loops
can be used to repeat a block of code multiple times, when a
specified condition is true. The syntax for a while loop is
while
while (condition){
//lines of Code to run while condition is true
}
The { } is used for a single or multiple lines of code, and does not
need a ;. Variables declared in { }, such as int kel; are only
accessible within the { } .
26 / 95
27 / 95
#include <iostream>
using namespace std;
/* Kelvin - Fahrenheit table
for fahr = 0, 15, ..., 120*/
int main () {
double min = 0, max = 120, step = 15;
double fahr = min;
13
14
15
16
17 }
Programs Output:
F
K
0
255.222
15
263.556
30
271.889
45
280.222
60
288.556
75
296.889
90
305.222
105
313.556
120
321.889
28 / 95
#include <iostream>
using namespace std;
int main () {
cout << "F \t K \n";
for (double fahr=0; fahr <= 120; fahr = fahr +15)
cout << fahr << "\t" << 5 * (fahr - 32) / 9 + 274 << endl;
return 0;
}
29 / 95
is equivalent to
Step before loop;
while (Condition) {
... code here repeats while condition is true ...
Step at end of loop cycle;
}
There is no difference between the two, except that the for loop is
more compact.
30 / 95
Comparison Operators
The comparison operators in C++ are:
Syntax
Operator Name
a == b
is
is
is
is
is
is
a != b
a > b
a < b
a >= b
a <= b
equal to
not equal to
greater than
less than
greater than or equal to
less than or equal to
31 / 95
1.4 if Statements
If-Then-Else statements allow you to branch your code down two
possible routes, depending on whether a condition is true or false
if (condition) {
// Code to be run if the condition is true
} else {
// Code to be run if the condition is false
}
32 / 95
Print random numbers and whether they are even or odd until the
sum of the numbers will be > 10000
1
2
3
4
5
6
7
8
#include <iostream>
#include <cstdlib> // for rand();
#include <ctime> // for time();
using namespace std;
int main(){
9
10
11
12
13
14
15
16
17
rnd.cpp
18
19
}
20
21
cout << num << "\t";
22
if (num %2 == 0){
23
cout << "even";
24
} else {
25
cout << "odd";
26
}
27
cout << endl;
28
}
29
30
return 0;
31 }
34 / 95
Logical Operators
The logical operators in C++, where A and B are logical expressions
(i.e. 2 == 1), which is evaluated to false or true, are :
Syntax
Operator Name
!A
not A
A and B
A or B
A
A
A
A
(true
(true
(true
(true
A && B
A || B
A != B
!(A && B )
!(A || B)
!(A != B)
xor B
nand B
nor B
xnor B
iff
iff
iff
iff
only one
A and B
A and B
A and B
of A or B are true)
not both true)
are false)
are false or true)
35 / 95
#include <iostream>
const int MIN = 0, MAX = 120,
STEP = 15;
36 / 95
37 / 95
#include <iostream>
using namespace std;
int main() {
char letterin;
cout << "Please enter a lower case letter: ";
cin >> letterin;
cout << "\n It is the "
<< letterin - 'a' + 1
<< " letter in the alphabet\n";
return 0;
}
cin.cpp
38 / 95
#include <iostream>
cin
char letterin;
letterin - 'a'+ 1
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream fout("1.5.2.1output.txt");
char lin; int iin, size = 5;
cout << "Please enter a lower case letter: ";
cin >> lin; lin = lin - 'a';
cout << "Please enter an integer ";
cin >> iin; iin = iin%26;
for(int i=0; i < size; i++){
for (int j=0; j < size; j++)
fout << char('a'+ (lin +(i*size+j)*iin)%26) << '\t';
fout << endl;
} return 0;
}
letterrandomise.cpp
40 / 95
#include <fstream>
iin = iin%26;
41 / 95
42 / 95
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin("1.5.2.1output.txt");
char c; int size = 5;
for(int i = 0; i < size; i++)
{
for(int j=0; j < size; j++)
{
fin >> c ;
cout << c-'a'<<'\t';
}
cout << endl;
}
return 0;
}
gridtonum.cpp
43 / 95
#include <fstream>
ifstream
ifstream fin("1.5.2.1output.txt");
This reads in a line from the file and puts one character into c
at a time.
44 / 95
1.7 Arrays
Arrays allow you to store a large number of values in a list so that
they can be used later in the program, the array has n spaces, but
goes from 0 to (n 1), where n is a const int:
type arrayname[n]
1 #include <iostream>
2 using namespace std;
3 int main() {
4
const int i=5;
5
int evn[i]={2,4};// Declare the array and set the first two
elements.
6
evn[2] = 6;// Set the 3rd (0,1,2) element.
7
for (int n=3;n<i;evn[n]=2+2*n++); // Fill the rest of the array
with even numbers
8
for (int n=0; n<i; n++) // Print out all the elements
9
cout << evn[n] << endl;
10
return 0;
11 }
evennums.cpp
45 / 95
Making Vectors
Vectors are in the vector library and are declared by:
vector <type> vectorname(size)
Note the round brackets (), arrays have square brackets [].
46 / 95
#include <iostream>
#include <vector>
using namespace std;
int main() {
int i=5; // Does not need to be const
vector<int> evn(i); // Note the ( ) brackets
// Elements can be accessed just like arrays with [ ]
for(int n=0; n<i; evn[n]=2+2*n++);
evn.push_back(12); // Adding extra values
evn.push_back(14);
for(int n=0; n < evn.size(); n++) // They know their own size
cout << evn[n] << endl; // the last element is evn.size()-1
}
return 0;
evennumsvector.cpp
47 / 95
1.8 Functions
returnType functionName (type1 argName1, type2 argName2 /*, etc
...*/ )
{
... code here ...
return (valueOfReturnType);
}
bits of computation.
They split a program up into different reusable parts.
Functions are called from other parts of the program, with their
name and parameter list.
functionName(arg1, arg2 /*, etc...*/)
Function Example - x n
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int power(int, int); // Function Prototype
int main() {
const int b = 2;
power.cpp
49 / 95
Things to Note:
Copies of the arguments are passed into the function.
afterwards is ignored.
here
).
50 / 95
#include <iostream>
using namespace std;
int power(int, int); // Function Prototype
int main() {
for (int i = 0; i < 10; i++)
cout << power(2,i) << '\n'; // Calling the Function
return 0;
}
int power(int x, int n){ // Function Declaration.
if(n>0){
return x * power (x, n-1); // Function Calls itself
} else {
return 1;
}
}
powerrecursive.cpp
51 / 95
#include <iostream>
using namespace std;
void swap(int&, int&);
int main(){
int a = 5, b = 7;
cout << "a = " << a << "\tb ="<< b << "\nswap\n";
swap(a,b);
cout << "a = " << a << "\tb ="<< b << endl;
}
void swap (int& x, int& y){
int z;
z = x; x = y; y = z;
}
53 / 95
#include <iostream>
using namespace std;
int a=2, b;
int sum () {
return a+b;
}
int main(){
b=5;
cout << sum() <<endl;
13 }
external.cpp
54 / 95
55 / 95
#include <iostream>
using namespace std;
int main(){
cout << sizeof(int)<< endl;
}
56 / 95
c:
...
...
...
Declaring Pointers
int c = 5; // Declaring an integer
int *p1; //Declaring a pointer to an integer (p1)
p1 = &c; // pointing p1 to c
int *p2 = &c; // Declaring a pointer to an integer (p2) and
pointing it to c
58 / 95
#include <iostream>
using namespace std;
int main(){
int a = 5, b = 7, c;
int *pa, *pb = &a;
pa = &b; // pa points to b
cout << pa << " contains: " << *pa << endl;
c = *pb; // c is set to the value pointed to by pb
std::cout << "c at " << &c << " contains: " << c << '\n';
*pb = 0;
std::cout << "pb at: " << &pb << " points to: " << pb
<< " containing: " << *pb
<< endl;
return 0;
}
0x7fff11232620 contains: 7
c at 0x7fff1123261c contains: 5
pb at: 0x7fff11232610 points to: 0x7fff11232624 containing: 0
pointing.cpp
59 / 95
#include <iostream>
using namespace std;
void swap(int*, int*);
int main(){
int a = 5, b = 7;
cout << "a = " << a <<
swap(&a,&b);
cout << "a = " << a <<
}
void swap (int *ipx, int
int z;
z = *ipx; *ipx = *ipy;
}
a = 5 b = 7
swap
a = 7 b = 5
pointswap.cpp
60 / 95
divided.
Segmentation Fault
A Seg Fault occurs when a program tries to access memory that it
shouldnt. This is usually caused by bad address arithmetic, or
reading elements much further than the end of an array.
61 / 95
#include <iostream>
using namespace std;
int main(){
char b[] = "Hello World", c = 'c';
char *ipc = &c;
while (true){
cout << *ipc++;
}
}
badaddress.cpp
62 / 95
Note: The Segmentation fault, and also that it prints Hello World,
and the program name a.out.
63 / 95
pb:
b:
b[0] b[1] b[2] b[3] b[4] b[5] b[6]
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;
int main(){
char b[] = "abcdefghijklmnopqrstuvwxyz";
char *ipc = &b[0];
for(int i = sizeof(b)-1; i>=0; i--)
cout << *(ipc+i);
cout << endl ;
}
pointarray.cpp
of a string is \0,
so b is 27 long.
65 / 95
Allocate
Free
Single Variable:
Array:
new type;
new type[n];
delete pointer
delete[] pointer
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
int num;
cout << "How many points? "; cin >> num;
double *points = new double[num];
10
11
12
13
14
15
16
17
18
19 }
Mean.cpp
67 / 95
#include <cstdlib>
delete [] points;
68 / 95
"Fish"
{C,a,t,\0}
"Cat"
"Elephant"
"Elephant"
C Strings are character arrays that are terminated by the '\0'. This
is so functions know were the end of the string is and do not need
to know its length.
69 / 95
Sorting C Strings
1
2
3
4
5
6
7
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main(){
char *wordlist[6] = {"cat","dog","caterpillar","fish","catfish"
};
8
wordlist[5] = "bat";
9
10
for(bool swapped=false; !swapped; swapped = !swapped)
11
for(int i = 1; i < 6; i++)
12
if (strcmp(wordlist[i-1], wordlist[i]) > 0){
13
swap(wordlist[i-1],wordlist[i]);
14
swapped = true;
15
}
16
17
for(int i = 0 ; i<6; i++) cout << wordlist[i] << endl;
18
return 0;
19 }
stringswap.cpp
70 / 95
#include <algorithm>
strcmp(wordlist[i-1], wordlist[i])
This compares the previous word in the list with the current
word. strcmp returns 0 if the strings are the same, a number
< 0 if the first is less, and > 0 if the first is greater.
swap(wordlist[i-1],wordlist[i]);
71 / 95
Type name[n][m]
array.
72 / 95
commandlineargs.cpp
program.
73 / 95
functions.
arrays etc.
All functions you want to use with the same function pointer,
74 / 95
Folding Vectors I
Left folding takes a value x and a list of values and repeatedly
applies x = function(x ,valueFromList), for all the values starting at
the top of list.
Here is a left folding function for integers:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <vector>
using namespace std;
int add(int a, int b){return a+b;}
int multiply(int a, int b){return a*b;}
int second(int, int b){return b;}
int foldl (const vector<int> &vecin, int lvalue, int(*function)(
int,int)){
for(unsigned int i = 0; i != vecin.size(); ++i)
lvalue = function(lvalue,vecin[i]);
return lvalue;
}
foldl.cpp
75 / 95
Folding Vectors II
14
15 int main(){
16
vector <int> nums(5);
17
for (unsigned int i = 0; i != nums.size(); ++i)
18
nums[i]= 2*i+1; // Fill vector with odd nums
19
cout << foldl(nums,0,second) << endl;
20
cout << foldl(nums,0,add) << endl;
21
cout << foldl(nums,1,multiply) << endl;
22
cout << foldl(nums,0,multiply) << endl;
23
24
return 0;
25 }
length.
As with all pointers, they are best avoided in C++ wherever possible.
Templates or derived classes should be used instead for type safety.
77 / 95
void*
Example
1 #include <iostream>
2 using namespace std;
3
4 int main(){
5
char a[] = "hello";
6
void *ptr; //Declare the pointer
7
8
ptr = &a; // Point it to a
9
cout << (char*)ptr << endl; // Typecast it as a (char*)
10
11
ptr = new int; // Allocate some memory for an int
12
*(int*)ptr = 43110; // Set the allocated memory to 43110
13
cout << *(int*)ptr << endl; // Typecast and dereference to an
int to print
14
15
return 0;
16 }
voidstar.cpp
78 / 95
3. Structures
3. Structures
79 / 95
field d :
struct structTypeName{
int i;
int d;
};
variables.
80 / 95
#include <iostream>
#include <cmath>
using namespace std;
struct point{ // Declare the point type
double x;
double y;
};
81 / 95
16
17 int main (){
18
point a = {3.0,4.0};
19
a = carttopolar(a); // Set a to the polar version of a
20
cout << a.x << " " << a.y << endl;
21
return 0;
22 }
82 / 95
avaliable at http://en.wikipedia.org/wiki/Operators_
in_C_and_C%2B%2B
83 / 95
#include <iostream>
using namespace std;
struct vector {
double x;
double y;
};
84 / 95
a->b can be used as a short hand for (*a).b, when you have a
#include <iostream>
using namespace std;
struct node{
int i; //An integer i
node *next; // pointer to the next node in the list
};
int main(){
node *head = new node; // 1st node
(*head).i = 1;
(*head).next = new node; // second node
(*(*head).next).i = 2;
head->next->next = new node; //a->b is the same as (*a).b
head->next->next->i = 3;
for (; head != NULL; head = head->next) // move head along the
nodes
cout << head -> i << " "; // Print out i in each node
cout << endl;
18
19
20
}
linkedlist.cpp
86 / 95
87 / 95
using namespace
Do not use using namespace in header files, as when they are
included the other code will inherit it. Instead refer to the function
directly using the scope resolution operator ::, e.g.
std::cout << "hi"<< std::endl;.
88 / 95
pow.h
89 / 95
power2.cpp:
1
2
3
4
5
6
7
8
9
#include <iostream>
#include "pow.h" // includeing the header file
using namespace std;
int main(){
for (int i=0; i <10; i++)
cout << pow(2,i) << endl;
return 0;
}
power2.cpp
90 / 95
statements (if-then-else)
It has #if, #else, #elif (else if). The end of the if statement it
needs a #endif.
#ifndef headername
#define headername
... Contents of header file ...
#endif
The more code you have the longer it will take to compile. If
you have a lot of code then it saves time to re-compile only the
parts that are changed and link together with the compiled
parts.
For this two things need to be done:
Split the code into multiple .cpp files, and put the function
Compile the .cpp files to object code separately, and link them
92 / 95
#include <iostream>
#include "mpow.h" // including the header file
#include "mpow.h" // including the header file
using namespace std;
int main(){
for (int i=0; i <10; i++)
cout << thomasmath::pow(2,i) << endl;
return 0;
}
mpower2.cpp
93 / 95
mpow.h:
1 #ifndef __mpow__ // if __mpow__ is not Defined
2 #define __mpow__ // define __mpow__
3
4 namespace thomasmath{ // the function is put in the thomasmath
namespace
5
int pow (int, int);
6 }
7
8 #endif
mpow.cpp:
1
2
3
4
5
6
7
8
#include "mpow.h"
// Function definition for pow in thomasmath namespace
int thomasmath::pow(int b, int e){
int out = 1;
for (;e >= 1; e--) out*=b;
return out;
}
mpow.h
mpow.cpp
94 / 95
g++ mpow.cpp -c
g++ mpower2.cpp mpow.o
this creates mpow.o which is a compiled version of mpow.cpp,
then this is compiled in with mpower2.cpp to produce the
executable.
95 / 95
References
References
96 / 95
References
References
B. Kernighan, D. Ritche, The C Programming Language, 1988
J. Nash, P. Dauncey, Introduction to C++, Blackett Lab, (2003)
D. Lee, First Year Laboratory Computing Laboratory, Blackett
Lab, (2006-7)
C++, http://en.wikipedia.org/wiki/C%2B%2B,
(6/11/2007)
http://www.newty.de/fpt/zip/efpt.pdf, (22/1/2008)
//www.cplusplus.com/doc/tutorial/pointers.html,
(25/6/2007)
97 / 95