0% found this document useful (0 votes)
19 views

Notes Pour Principles and Practice: Using C++

The document provides notes on chapters from a C++ textbook. It defines key terms related to C++ programming such as data types like int and string that are used to store different types of data. It describes basic programming concepts like functions, parameters, return types, and comments. It also covers input/output streams, variables, constants, expressions, and control structures like if/else statements and loops. Object-oriented concepts such as classes and structs are introduced as user-defined types that can contain functions and data. Exceptions and error handling are also summarized.

Uploaded by

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

Notes Pour Principles and Practice: Using C++

The document provides notes on chapters from a C++ textbook. It defines key terms related to C++ programming such as data types like int and string that are used to store different types of data. It describes basic programming concepts like functions, parameters, return types, and comments. It also covers input/output streams, variables, constants, expressions, and control structures like if/else statements and loops. Object-oriented concepts such as classes and structs are introduced as user-defined types that can contain functions and data. Exceptions and error handling are also summarized.

Uploaded by

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

Notes pour Principles and Practice

Using C++

Chapitre 1————— Computer, People, and


Programming

int : storage of integer


string : storage for a string of
character
CAD/CAM : Computer-aided
design/computer-aided
manufacturing
GUI : Graphical User Interface
Chapitre 2————— Hello World!

std::cout : character output stream


[ prononcé “see-out” ]
\n : special character for creating
new line
// : démarcation des commentaires,
tout ce qui vient après sur la ligne
est un commentaire
# : sign for a preprocessor command
(before compiling)
#include : directive to give
access to facilities from a header file
[basically it copies another file at
the start of another file] [ <…> for
the name of a std libraries or “…”
for the name and extension of a
programmer-defined header]
#define : directive to define a
macro [doesn’t require a ‘;’ at the end
of the line]
main : function to indicate to the
computer to start executing the
program
statement : part of a program that isn’t
an #include directive
———————————————————
———————
▶︎ commencer chaque programme
par un commentaire descriptif de la
fonction générale du programme
▶︎une fonction est une séquence
d’instruction nommé et définit par 4
partie : return type, name, parameter list,
function body
ex. Int main () {}
▶︎le compiler transforme le source
code de C++ en object code qui peut
être ensuite exécuté par
l’ordinateur
▶︎le linker associes l’object code
compiler à celui des librairies
utilisées

Chapitre 3————— Objects, Types and


Values

object : region of memory with a type


to specify what it contained
variable : named object
std::string : variable type for characters
[holds also the number of characters]
int : variable type for integer
double : variable type for floating
points numbers
char : variable type for individual
character
bool : variable for logical variables [true
or false]. converting int into a bool,
0==false and everything else is true
(donc si a==0, if( a ){} won’t get
triggered)
definition : statement that sets asides
memory for a new variable
std::cin : character input [prononcé
“see-in”]
operators : sign to apply an operation
on a variable [liste p. 66-67] [liste
avancé p. 97-98]
/ : divide [lorsque appliqué sur
int donne un int]
% : remainder (modulo)
!= : not equal [can be used to
flip the value of a boolean result
from 0 to 1 or invertedly]
concatenation : often used to describe
the linking of two string
‘\n’ : name for newline [“end of
line”] in output
sqrt() : named fonction for square
root [donne tjrs un double]
if() {} : selects action based on
conditions (if-statement)
else : position after an if-statement,
it gives the indication to the
computer on what to do if the
condition isn’t satisfied
= : assignment [gives a variable a new
value / ne veut pas dire égal]
while() {} : while-statement [works as
long as the operation in brackets is
working]
assignment : to place a new value into
a variable
initialization : to give a variable it’s
initial value
———————————————————
——————
▶︎to add 1 to any variable, just add
++ before it (ex. b = b+1 devient
simplement ++b)
▶︎in general, for any binary
operator (oper), a oper= b means a = a
oper b [+=, -=, *=, /= and %=]
▶︎a name starts with a letter and
can only contain letters, digits, and
underscores [ ∅ space] [ ∅
keywords (voir p. 1082)]
▶︎the name “x” is conventionally
used for a local variable or
parameter, “i” is usually reserved
for a loop index.
▶︎All Caps is usually reserved for
macros (voir p.1055)
▶︎you can convert some type from
one to the other : ⎚ bool to
char
⎚ bool to int
⎚ bool to double
⎚ char to int
⎚ char to double
⎚ int to double
‼only why they are both of
similar sizes‼
▶︎by using the {}-list notation,
rather than the = notation, for
initialization, the program outlaws
narrowing conversions [based on
the universal and uniform initialization list]
Chapitre 4————— Objects, Types and
Values

I/O : Input / Output


arguments : inputs to a part of a
program
results : outputs from a part of a
program
operand : a variable or a value
involved in an operation
expression : computes a value from a
number of operands [comme une
opération mathématique]
constexpr : constant expression of a known
value [a symbolic constant cannot have
it’s value changed after it’s
initialization] [the value needs to be
known at compile-time(so it can only
refer to other constexpr variable or
value)]
const : creates a constant definition
that cannot be change after
initialization even if it’s value is
unknown (ex. n+1) [const applies to
the thing left of it. If there is
nothing on the left then it applies to
the thing right of it.]
const member : in a class, if const is
used at the end of a member
declaration, it will not be able to modify
it’s object. Usefull in the case of a
function member used to read into a
variable of that type that could be const
const function : guarantees to keep
all of it’s parameters or member variable
as const. It can return a value but
cannot initialize a member or pushback
elements. (To use as much as possible
to avoid unwanted behaviour)
literals : fixed values (constant
expression) used for representation
inside the code. (ex.: 1, 2.5, ‘a’ )
lvalue : short for “value that can
appear on the left-hand side of an
assignement”
rvalue : opposite of lvalue
[basically lval==object reference and
rval==value]
switch() : switch-statement [only
usable with int, char or enumeration]
break : ends a loop. It is needed
after any case from a switch-statement to
terminate it [otherwise it just drops
through the next case’]
default: : position after a switch-
statement, it acts similarly to the else
continue : jumps to a new iteration
of a loop
iteration : repetition for a series of
elements of a data structure
‘\t’ : tab character
block : sequence of statements
delimited by { } [it’s also called a
compound statement] [the empty block
can be use to ask for nothing]
for() : for-statement [concentrate
the control variable in the brackets
which means it does not require
the initialization of the variable]
[loops as long as the statements in
bracket stay true]
function : named sequence of
statements [ defined in a similar way
to a variable ex. int square(int x){return
x*x}; ] [a void function can still return
another function]
return : in the function-body (the block
of the definition), defines what the
function does with the variable
member function call : function of the form
object_name.member_function_name
std::vector : sequence of elements
accessible by an index of constant
size after initialization [the indices
start from 0 and increase by
increments of 1] (also reffered to as
dynamic array)
[to refer to
one element of a vector you put the
name of the vector followed by the
index number in bracket (ex. v[2] )]
__.size() : member function call that
give the number of elements of the
vector __
0:__.size() : range for a vector __
using a half-open sequence [can be
used to create range-for-loop]
__.push_back() : member fonction call
that adds a new element to the
vector __ at the back of the index
growing a vector : to add elements
to a vector after having started it as
an empty vector
__ x : v : half-open sequence of
elements [means: for every x of the
type __ that’s in the vector v]
sort() : organize the elements of
a vector [ contrairement au livre, la
fonction nécessite un début et une
fin (__.begin(), __.end())]
erase() : deletes the element
pointed to by the iterators used as
arguments [when erasing a range, the
element pointed by the iterator for last
isn’t included]
|| : “or” logical operator (ex.: if( a==1 ||

a==2 ). )
———————————————————
——————
▶︎pour obtenir des double dans les
formules plutôt que des int, il faut
ajouter .0 au chiffre à convertir (ex.
5/9 —> 5.0/9)
▶︎pour les fonctions de la librairie
standard, on peut seulement
déclarer la fonction sans la définir
complètement [on met le point-
virgule directement après la
première ligne]

Chapitre 5————— Errors

error(“ ”) : outputs the error


message put in brackets and stops
the program (acts a lot like a return
but with a message)
return : returns the flow of the
execution to the function from
where it is called
stoi() : function to convert a string into
an int
exception : throwing an error to a catch
rather that the normal return
throw : creates an exception that
refers to the appropriate catch by
both reffering to a previously
created class type (either standard
or not)
catch () : gives the instructions after
a throw (can also work for standard
subscript exceptions)
catch(…) : catchs any unspecified
exceptions
out_of_range : standard class type for logic
error of range
if(cin) : if-statement with the condition
that the last read succeeds
if(!cin) : if-statement with the
condition that the last read didn’t
succeed
void : when used for a function, it
creates a function that doesn’t
return a value
cerr : mostly like cout but used for
error outputs
_.what() : extract the message
cast : means type conversion
<__> : used to specify a type
&& : “and” logical operator
! : “not” logical operator
———————————————————
——————
▶︎a variable is a memory location that stores a
value (data) as opposed to a function which
holds executable code (instructions)
▶︎the “void” is used basically like a “not-
specified” sign that can be used to not give a
type or a parameter to a function (however, an
empty function parameter list is now equivalent
in C++20)

Chapitre 6————— Writing a Program

class : keyword used to mean user-


defined type. Private by default
struct : almost exactly like a
class but public by default [by
convention more than by obligation,
a class is used when private
elements are to be expected]
members : defines what an user-
defined type can hold. There can be
more than one for a single type [on
peut ensuite définir la valeur pour
chaque membre en ajoutant .___ à
l’assignement]
constructors : allows user-defined type
to be initialized with multiple values
at the same time by giving the
instructions on what member should
hold each value.
default : used with a
constructor to explicitly make it
the default constructor [ex.: Foo() =
default; ]
while(true) : will loop as long as the
code inside the loop allows it. Can
be stopped with a break inside the
loop.
while(cin) : will enter the loop as
long as all the previous cin worked
[the input being inside of the loop,
it will have to finish it’s execution
one last time before breaking]
while(cin>>__) : the cin is in that
case part of the while condition
[the cin is entered before the check
of the conditions so when it doesn’t
work, the loop immediatly stop
without having to be executed one
last time]
public : allows variables to be used
outside of a class or struct
private : doesn’t allow variables to be used
outside of a class or struct
protected : private but allows variables
to be used in sub-classes
cin.putback(__) : puts a specified
variable back into the input stream [the
variable doesn’t need to be taken
from the stream]
endl : acts in a similar way to ‘\n’ but
flushes the buffer output. It’s also a
function which means it isn’t a char
type.
flush : like the endl but without giving
a newline (makes it basically hidden)
buffer flush : transfering the computer
data from one temporary storage to
the permanent memory of the
computer (like a save button)
global variable : declare outside of the
functions [by convention at the
top], the global variable stays
intact throughout the whole
program [it is not influenced by the
scopes]
———————————————————
——————
▶︎it’s a good idea to out a test
inside of a void function, this way it
can stay dormant when it isn’t
required (adding a return a the end
will signifie that everything
worked)
Chapitre 7————— Completing a Program

<cmath> : library for all of the


standard mathematical functions
fmod() : function from the standard
library to give a modulo operator
applicable with double [accessible
throught <cmath>]
/*____*/ : block comment
Try{} : try-block
greater() : makes it possible to sort a
vector in the opposite order
auto : self-defined type based on the
initialization [used for c++11 and
forward]
concatenation : fusion of two strings into
a single one [uses the “+” operator]
getline() : function with a similar effect
to cin but it allows for multiple word
and multiple lines of texts
round() : function to round a double to
the closest integer
———————————————————
——————
▶︎the ‘>’ character is often used as a
prompt for the user input

Chapitre 8————— Technicalities:


Functions, etc.
declaration : statement that introduces a
name into a scope and specifies a type
for it
extern : keyword used before the
type of a variable. it then declares
the variable without defining it.
[compiler will go search for the
definition of the same variable
inside of another source code file]
pow(_,_) : function from C to return an
exposant operations with double [1ere
valeur est la base et la deuxième la
puissance]
continue : jumps to the next iteration
of a loop by skiping all the
statements after it without
breaking the loop
do{…} while() : like a while() loop but
the first iteration is executed
before checking the condition of
the while statement
float : variable type like double with the
only difference being that it takes
only 4 bytes instead of 8 which
lowers drastically it’s accurary [it
can’t be use for a comparison or for
a precise result]
long : type modifier to be used for large
numbers. It can be added to itself or
a double to increase the type’s range
otherwise it will take a integer
short : type modifier that can be
used for small numbers when you
are sure that it will only that small
values
signed : default int type modifier
unsigned : type modifier that only
allows for positive numbers
static : type modifier that makes a
variable memory allocation constant
[similar to creating a global variable
but private to a single source code file]
[in a class, allows a single instance
of the variable for every call of the
class]
typedef : used to associate explicitely
a type or a class type to an
identifier [ex.: typedef int amount;
(amount type will be the same as int)].
sizeof() : operator to check the size in
bytes
union : used to group different type
of variables together under a single
name. unlike a class or a struct,
memory is shared between the
variables which means that a new
value overwrites the precedent one
making it more efficient.
find() : function in the algorithm
library to find something inside of a
vector
cin.ignore() : ignores the next value in
the input stream
<iostream> : one of the standard
library header file that combines at
the same time the istream[inputs] and
the ostream[outputs]
array : like a vector but with a fixed
and predefined number of elements
[a vector is basically a dynamic array]
[an array passed by value will
automatically decay into a pointer
to the first element of the array]
std::array<_,_>__ : C++ array is
basically a small container of
functionnalities over the C array that
makes it function more like a type. It
can be returned and passed by value
without decaying. afterwards referred
like normal
scope : region of program text
(something in scope as already been
declared precedently) (not in scope
would be ex.: two functions in the
wrong order with a reference from the
first to the second one) [nested in
multiple strats]
overloading : giving multiple
declarations for a single name but
with differents arguments. The
compiler than picks the right one
for each situation according to the
argument type
abs() : function to return the absolute
(positive) value of an integer (ex.: abs(-
5)==5) [<cstdlib> for int] [overloaded in
<cmath> for use on double]
swap() : standard function to
exchange the value of two object.
works with every type.
static_cast<>() : used to convert
between types in a clear way
constexpr functions : function type to create
a simple calculation which only
includes constexpr as arguments and
that is calculated directly at compile
time
namespace : grouping of declarations
for functions or classes
:: : operator to specify the
namespace before a declaration, creating
a fully qualified name which avoids
problems from conflicting names of
two different libraries
using namespace ____ : gives a
default namespace that is being used
as long there isn’t another library
being referred to by a fully qualified
name [shouldn’t be used in a header
because it’s hidden]
#pragma : keyword to specify
compiler directives, which can
change the default behaviour of the
compiler
#pragma once : included inside a
header file, it prevents it from being
included multiple times inside a
single file. otherwise classes or
functions could get duplicate
declaration, creating an error.
#ifndef : means “if not defined”, it will
do the followind preprocessing upuntil
it reaches the #endif [basic and
legacy alternative to #pragma once]
#endif : ends the #ifndef
macro : a name that is replaced by
the value asigned to it at the #define
whenever it’s name is encountered
in the source code [to define a
multi-line macro, it is necessary to
put a ‘\’ at the end of each line]
printf(_,_) : print function in the C
library, takes a string (like a
message) which is called format [it
can have an embedded format
specifiers [%_] which is going to
influce the output of the value] and
a value to be outputed.
%d : format specifier for a
signed integer value
std::pair : standard data
structure(precreated class) to
combine two types on a single
variable [std::pair<type1,type2>
nameofpair (value1,value2)] (in
<utility> header) (if neccesary many
times, better to use a struct)
__.first : first value of the pair
__.second : second value of the
pair
std::tuple : generalized version of
std::pair (in <tuple> header)
std::get<__>(__) : function from
<tuple> to get a value from a tuple.
(position dans les guillemets, nom
du vecteur dans parenthèses)
———————————————————
——————
▶︎a definition is a declaration that also
specifies the entity declared
▶︎to pass by reference is to create
a copy of an existing variable to
use in a function, which will then
replaced the original value with the
copied one. [ex. Void function(int&
a){} is going to pass ‘a’ by
reference]
▶︎you cannot nest a function within
another function but most of the
other scope nesting cases are
possible (like function in a class;
class in a class; class in a function;
…)
▶︎you can leave function
arguments unamed if it isn’t used.
so if a lot of other code calls that
function, it doesn’t need to be
updated even if you change the
function and don’t use that variable
anymore
▶︎you can fall throught main()
without getting a return error. it
will by default return 0.
▶︎a return call for a void function will
simply end the function in the same
logic as a break would end a loop.
▶︎you can pass a value into a
function by const-reference. This allows
to use a value without having to
copy it while still making sure that
the value won’t get modified by the
function [ex.: void print(const int&
x){} ]
▶︎you can also return a value by
const-reference
▶︎a pass-by-reference needs to
pass a variable and cannot pass a
direct value.
▶︎a namespace directive can be
used inside of a function body,
reducing the probability of mixing
because it gets limited to the
scope of the function.
▶︎macros should be limited as
much as possible because they are
preprocessed, creating often
unintuitive results and/or reading
difficulties. This also mean that the
syntax isn’t checked until they are
done

Chapitre 9————— Technicalities: Classes,


etc.
Inheritance : to define a class by referring
to another one. You can than have
a general class with functions for
all cases and derived classes, that
takes the general class and adds
the specific functions for a more
specific case
Interface : public part of a class
Implementation : private part of a
class. the user gets indirect access
to it throught the public functions
using the private members of the
class
Constructor : member function with the
same name as it’s class [a object
from a class with constructors
needs to be initialized at
declaration(with a list of value in
“{}”)]
Object : memory allocation for a
class. (the name is optional, ex.:
when used to initialize a lval)
:X(x), Y(y){} : member initializer list
used with constructors. [as
opposed to the ‘=‘ notation, the
members are initialized when
needed as opposed to be given a
default value at compile time]
enum __ {} : variable type that can hold a
list of constants with, by default,
an int as a tag. This tag can be
changed at initialization or later
[This means that the names in an
enum cannot be reeuse for some
other source code]
you can declare a variable
directly after the enum list, however it
decreases source code readability in
my opinion. The declaration of an enum
is basically only the creation of a
new and very specific type
enum class __{} : more typesafe and
more limited in scope than a basic
enum. The namespace syntax is
neccesary to access the data
inside the enum. [you can also
specify the type of variable with a
‘:type’ before the ‘{}’]
[you cannot do an implicit
conversion of an enum class to an
int because every int values
doesn’t neccesary have a
corresponding value in the enum
class type] [from C++11 so more
modern]
operator__ : keyword to overload an
operator [at least one of the
operands needs to be of a user-
defined type] [can be very useful
for an enum] [you add to the
definition of an operator for a new
type, but you cannot expand on it]
os : output stream [basically it’s the
general version of the cout which
can only print on the terminal] [you
can pass the os as a parameter to a
function by giving it the type ostream& ]
unary operators : operators that acts
on only one operand of an
expression [ex.: ‘++’ (plus
increment) which only looks at one
variable]
binary operators : operators that acts
on two operand of an expression
[ex.: ‘<=‘ (less than or equal) which
looks at two variables]
Ternary Operator : short Hand if… Else. The
if is replaced by a ‘?’ (Following the
condition as opposed to before like
normal) and the else is replaced by
‘:’
(_)?_:_ : also called an arithmetic if
or a conditional expression, it is an
abbreviation for a simple if-statement
[structure: (condition) ?{case for
condition met} : {case for else}]
in-class initializer : initializer of a class
member specified inside the
member declaration [basically the
default value of the member]
friend : keyword used inside a class
to define something outside of that
class as a friend of the class. The
function, or class, without being a
member of that class will have
access to all private or protected
members of that class.
__.c_str() : function in <string> to
convert a c++ string to a C-string [returns
a c_string]
__.strtok(__,__) : <cstring> function
that sequences the string into segments
created by delimiters. Takes a c-string
(to change for a NULL on
subsequent calls) and a string with
the delimiters char. Results is NULL
when done.
this-> : the this pointer is used inside of
member functions in order to point explicitly
to a member variable of the class. This
can be used in the case of a member
variable having the same name as a
parameter from the function.
<ctime> : header file to read and
interprets the date from the
computer internal clock.
time() : gets the current time
value of the internal computer
clock an return a variable of time_t
time_t : type for a time
struct tm : time struct with 9 members
to broke down the date into
meaningfull integers
localtime(const time_t* __) : Takes in
a pointer to a variable of type time_t and
converts it into a struct tm for the local
time-zone
asctime() : converts a struct tm to a
string [format: Www Mmm dd hh:mm:ss
yyyy]
ctime() : equivalent to doing
asctime(localtime(const time_t* __))
strftime() : a lot like asctime() but
with specifiers for the string output
inline : keyword for functions or variables
to get multiple implementation with
multiple translation unit. Necessary
if external linkage is needed
inlined function : old meaning of inline.
Replaces the function by it’s code,
making it inline of the rest of the
code instead of a function call.
(faster when used with simple
functions) [automatically used by
the compiler optimization]
__attribute((always_inline)) : force the
compiler to do inline optimization
for the function attach to the
attribute
internal linkage : The name can be
referred to from all scopes in the
current translation unit.
external linkage : The name can be
referred to from all translation units
to string() : function to convert other
types into a C++ std::string
stod() : string to double function
stof(): string to float function
———————————————————
——————
▶︎standard library types are still
considered to be “user-defined”
because they still need the
declarations for the std headers to
be recognized
▶︎a class can be separated as being
a state and a set of operations that can
be applied to that state
▶︎a the function members of a class can
also be separated in two sets. The
ones necessary for data
representation and the interface,
and the helpers functions which build
upon the interface for convinience
without being needed
▶︎you can define members of a class
outside of it’s declaration using the
namespace notation
“class_name::member_name” [helps
readability if the definition is large and
the class doesn’t need to recompile
changes made to the body
everytime it gets changed] [as a
rule of thumb, don’t inline the
function body if it’s more than 5~6
lines]
▶︎a user-defined type most likely will
need a default construct (a constructor in
the case of a declaration for a new
variable with no explicit initialization)
[the default values can be directly
on the variables for easy access
(see p.329)]
▶︎we use ‘(_)’ after a vector to
specify the number of elements
inside of it (ex.:
vector<char>lettre(10); )
▶︎when using headers, the ‘.cpp’ file is
associated automatically to the ‘.h’.
So it shouldn’t be included inside of
.main because it will cause a duplicate
error.
▶︎the operator overload for ‘!=‘ is
automatically created by the compiler
if the overload for ‘==‘ is defined

Chapitre 10————— Input and Output


Streams

<fstream> : header file that combines


<ifstream>(file input) and
<ofstream>(file ouput)
fstream : type for a variable that will
represent the file that’s used for
output. the variable will then have to
replace the cout (ex.: FileVariable<<)
ifstream or ofstream : type for
a variable specific for respectively
an input or an output
fstream __ {__.extension,ios::app} :
definition of a variable fstream with a mode
specifier to ask to append to an
existing file instead of overwriting on
top of it.
mode : in ios(input/output stream)
namespace, the give instructions on
how to deal with a file
__.open(__) : function to access a
file. (can of the initialization of the
variable so not neccesary if it was
already defined at declaration)
__.is_open() : boolean function to
check if a file is open
__.close(__) : function to close the
access to a file. no need to use it if
it isn’t explicitly required because
it will be call implicitly at the end of
the scope
stream state : 4 different possible bool
states for input stream (ex. if(cin.eof())
return; )
__.good() : all of he operations
succeeded
__.eof() : the istream as reach the
end of the data (abreviation meaning
“end of file”)
__.fail() : the operation didn’t all
succeed because something
unexpected happen (like trying to
read a char into an int variable)
__.bad() : a serious and more
broad problem happen while trying
to read the file (like a disc read
error)
cin.unget() : function to put the last
input read back into the stream
[specific version of cin.putback, which
can only return the last char read
(basically a “undo” function)]
cin.clear() : clears the input stream
buffer and sets the stream state
back to good [except if a state flag
is explicitly defined in the
brackets]
cin.peek() : reads a char into a variable
without moving the read pointer in
the stream(can be used to check a
input without needing a putback after
the check)
cin.exceptions(cin.exceptions() |
ios_base::badbit) : statement to specify
cin to throw std exception ios_base::failure if
it’s stream state goes to bad().
(simplifies source code by reducing the
number of checks for each input)
__.reserve(__) : vector function to request
a certain amount of space to be
used in memory for the number of
objects specified as parameter. [used
for optimisation, because the vector is
copied everytime it expands]
__.emplace_back(__) : vector function like
a .push_back() but the object is
created directly inside the vector
which prevents from having to copy
it. Uses it’s arguments as parameters of
the function instead of the variable
destructors : does the opposite of a
constructor by giving instructions
on how to remove a class object.
(has the same capabilities as a
constructor, but way less actual
utility) [syntax the same as
constructor but with a “~” before]
string literals : read only value of a string
written with brackets in the source
code. There is always a ‘\0’ char
added at the end of the string to
signify it’s end and two of them put
side by side will concaternate before
adding the ‘\0’
R”(__)” : the ‘R’ prefix specifies a raw
string. It requires to put ‘(‘ and ‘)’ to
close the string. If parenthesis are
needed inside, delimiters (any char
not needed inside) can be use
outside of the closing parenthesis
to define the string
std::string_literals : namespace for the ’s’
suffix. inline of the std::literals
namespace
“__”s : the ’s’ suffix will create a
raw std::string literal rather than a c-style
string literal (can be usefull to pass as
parameter in a function that only takes
std::string) (also used when the auto
keyword is assigned to it)
__.pop_back() : function to delete the
last element of a vector by reducing it’s
size by one
__.back() : function to access the last
element of a vector
__.insert() : function to insert data
anywhere inside a vector without
overwriting the previous data,
basically it extend the vector by 1
and moves all elements after it by 1
position
>>noskipws : short for “no skip white
space”, flag to specify to the input
stream to also input the whitespace
>>skipws : flag to specify to the
input stream to skip the white
spaces
———————————————————
——————
▶︎when writing data into a file,
instead of using a symbol between
each info, a simple space char is
better because it is better
implemented into the io and string
libraries. Symbols can than serve to
regroup an info which would
contain a space char(like a title or
a name) and which are most likely
going to be a smaller part of the
info line. (this also improves
readability of the raw data)
▶︎apostrophe ( ‘ ) can be used to
separate a integer into easy to read
sections inside of the source code
without it changing the actual int

Chapitre 11————— Customizing Input


and Output

sticking : said of a manipulator which is


going to change the behaviour of
the iostream up until another
manipulator says otherwise
fields : a field is the amount of char
position needed to express a variable in
a text format
int iostream flags : manipulators for input
and output of integer values
(>> or <<) hex : flag to specify the
use of the hexadecimal form on all
futur integer output
(>> or <<)oct : flag to specify the
use of the octal form on all futur integer
output
(>> or <<)dec : flag to specify the
use of the digit form on all futur integer
output
<<showbase : flag to add a prefix to
futur int output in order to
differenciate between the different
forms [‘0’==oct and ‘0x’==hex] (the
same prefixs work for int literals in
the source code to specify a different form than
used)
<<noshowbase : flag to not show
the int prefix to the output [also the
default]
cin.unsetf(ios::__) : function that
means “unset flag” (for the source code
to implement the int form prefix’s, all
the default flags must be cleared)
<<setw() : manipulator function to set the
field width of an output [works with int,
float and string] [this function doesn’t
stick] [if the char width set isn’t
reached the char left at the
beginning are left as empty spaces]
float iostream flags : manipulators for
input and output of floating point values
(>> or <<) fixed : flag to specify the
use of fixed-point notation which
doesn’t round the number
(>> or <<) scientific : flag to specify
the use of the mantissa and exponant
notation
(>> or <<) defaultfloat : chooses
depending on the case between
fixed and scientific (as a default
precision is of 6 total digits)
(>> or <<) setprecision() : manipulator
to set the number used for the
precision of a float [the precision [the
defaultfloat precision defines the total
amount of digits, but the other
two’s define the amount after the
decimal point]
__.seekg() : iostream function to move the
reading position (seek’g’ stands for
seek“get”) to the number used as
parameter. (stream position, like a vector,
starts from 0) [behaviour after eof()
is undefined]
__.seekp() : iostream function analog to
seekg() but for outputs (seek’p’ stands
for seek”put”) (the program will,
when adding new outputs, replace
the old data with the new one)
[behaviour after eof() is undefined]
__.tellg() : iostream functions to tell
the position of the get(“input”)
pointer
__.tellp() : iostream function to tell
the position of the put(“output”)
pointer
<sstream> : std librairy header combining
all classes in relation to stringstreams
stringstream : type of stream that works a
lot like an fstream but instead of a file
name, it takes a string variable (usefull
to convert a string type into
something else as if it was a
classic cin or cout while everything is
kept as internal)
istringstream or ostringstream : type of
stream exclusive for a string input or a
string output
__.str() : <sstream> function that return a
copy of the string inside of stringstream
[basically works as an input from
the stream]
__.str(__) : <sstream> function overload to
set a copy of the string in parameter
as the new string inside of stringstream,
overwriting the previous stream
[basically works as an output to the
stream]
__.get(__) : <iostream> function for a char
input that doesn’t skip the
whitespaces. If a char array with the
amount of char needed is put in
parameters (ex.: cin.get(c,10). ), the
function will input the c_string
instead of a single char
tolower(__) : function to turn a char
into it’s lowercase equivalent
toupper(__) : function to turn a char
into it’s uppercase equivalent
(limited by certain languages where
not all letters have an uppercase
variants)
\” : special char to replace the
normal ‘ “ ‘ char that would create
confusion with it’s use inside of the
source code as a delimiter for string
literals
__.rdstate() : <istream> function to read
the state of a stream (the states can
add up, so in the case of a ios::badbid,
the state will also output ios::failbit)
bitwise operator : operators that works on
bit size binary level (usefull to get
logic from flags and states)
‘ & ‘ : bitwise “AND” binary operator
(ex.: cin.rdstate() & ios::failbit ) [if a
certain bit is 1 in both of the two
variables, the output will be 1 for that
position] (in that case, if ios::failbit
is inside of cin.rdstate() than output > 0 )
‘ |’ : bitwise “OR” binary operator
(ex.: ios::flag1 | ios::flag2 ) [if a
certain bit is 1 in either of the two
variables, the output will be 1 for that
position]
‘ ^ ’ : bitwise “XOR” binary operator
(ex.: ios::flag1 ^ ios::flag2 ) [if a
certain bit is 1 in only one of the two
variables, the output will be 1 for that
position ]
bitmasks : a bitmask can be used to
isolate a single bit flag for a variable
with multiple flags. to use binary
operator ==, simply use the ‘&’ bitwise
operator with the variable to isolate the
necessary flag first
———————————————————
——————
▶︎1 byte == 8 bits on a PC
▶︎there are multiple std bool functions
to check char classification (see p.397-398).
this makes it easy to seach for a
certain category like digits,
numbers, whitespace…
Chapitre 12————— A display model

stack allocation : scope-limited memory


which works as a continuous line.
the allocation of it’s memory is
automatically taken care of by the
compiler. it’s also considered safer
and faster, but as more limitations
than the heap
heap allocation : the program as to
specify when the heap should be
used and the allocation and de-
allocation as to be specified in the
source code. useful if an object is
needed outside of it’s scope or if
the stack is too small.
new : keyword used before a variable
to allocate it to the heap. It will
check what data type is being
allocated and the space needed for
it and than find the space inside
the heap. it will then return a
pointer to that memory address
delete : keyword used to de-allocate
a variable from the heap
-> : operator that works just like the
‘.’ operator but for pointer variables.
it basically dereference the
variable pointer into the simple
variable before using it [like a
abreviation for (*var).function() ]
<stdexcept> : std lib header file which
defines a set of standard
exceptions which will throw
automatically inside of a try-block
virtual : keyword for member function
declared within a base class and to be
overriden by a derived class. When a base
class object reference or points to a derived
object, a call to a virtual function will call
it’s derived form
void* : void pointers are used to point to
a address in memory, without
specifying any type for it’s data to
be translated into at that location
typedef : keyword to create alias for
existing data type. Used in order to
show more descriptive,
understandable and specific info as
the data types
———————————————————
——————
▶︎go to the fltk section for more info
related to chap 12

Chapitre 13————— Graphics Classes

find() : function in <algorithm> to


abreviate the simple while() - if() loop
to find a specific value inside of a
range
adjacent_find() : function in <algorithm>
that looks for two equal and
adjacent variables inside of a range.
(useful combined with a sort() to
weed out duplicates)
std::initializer_list< __ > : std type in
<initializer_list> to access an array
of objects of the type specified in
brackets. (more optimal instead of
a vector when passing an
undefined number of elements to a
function)
template < __ > : used to create
generic models that aren’t type
confined. A placeholder name is
given inside the brackets, and the
function or class follows it in it’s
usual form, but using the
placeholder when needed
typename : keyword used in template
declaration to identify our placeholder
name as a type. (the class keyword can
also be used instead but it is less
general) (ex.: template <typename T> void
foo(){} )
<=> : three way comparison operator. it
combines all comparison operator,
returning either (> 0) if(a > b), 0 if(a ==
b), or < 0 if(a < b). [overloading the three
way will also automatically overload
the 6 other individual operators]
#undef __: ends the scope of a macro
#define __(x) # x : function macro that will
replace the function with a string literal
composed of it’s parameter name (ex.:
if #define foo(x) # x —> foo(x) would
become “x”)
#define __(x, y) x ## y : function macro
similar to the last one, but that will
takes two arguments, concaternate
them, and then transform the
function into a string literal (ex.: if
#define foo(x,y) x ## y —> foo(x,y)
into “xy”)
predefined macros names : multiple
constants are created as macros with
every compiled instances of C++, they
can then be used in code as stable
and crossplatform constants.
[ most of the time in the form of: _
_ FOO _ _ ]
std::map : like a vector but with a
custom key assigned to each value
instead of only an int order index.
(much more optimized to seach an
element from a large list when their
relations to each other isn’t
needed)
std::unordered_map : subset of a map with
the difference of it’s element not
getting ordered. It’s faster but with
the drawback of losing
functionnalities
std::accumulate() : function in <numeric> to
use a binary operator on a range. Usefull
in order to give clearer
understanding and abreviate a for
loop with a single task. [by default,
the function uses the ‘+’ operator]
anonymous class : anonymous classes can be
used if a class member needs to
behave as if it’s members where part
of the base class (like for a tagged
union inside of a struct)
tagged union : basic struct which
assemble a enum tag to each union
state. Can then be used with a enum
variable to check what type the union
is holding. (Saves storage over a normal
struct however it’s more prone to
errors)
std::variant<__> : class template in <variant>
that creates a tagged union with added
functionnalities and compatibilities
std::holds_alternative<__>() : bool
function from variant to check if the type
in brackets is used inside of the variant
variable used as argument
std::monostate : unit type in <variant>.
Used as the empty state of a variant
because if none of it’s member are
default-constructible, the monostate will be
able to make it default-constructible
std::get<__>() : function overloaded for
variant and used to return it’s data in
the form of it’s type used in brackets. If
the types don’t match, it create’s
an error
std::get_if<>() : same function
as get<__>() but
emplace<__>() : function overloaded for
variant to create a new value in place
inside of an exisiting variant. If no
variant’s type conflict, it can also be
done with the ‘=‘ operator
std::memmove() : copies objects pointed to
by the first argument to in place of
the objects pointed to by the second
argument. the third arguments gives the
amount of elements to copy (ex.:
stdmemmove(str+1, str+4, 2); )
std::remove() : instead of erasing each
element, it moves elements to the end of
the array. it also uses find() to aim at
an element instead of position iterators.
Can be an argument of erase() to
erase the unwanted backend after
std::remove_if() : like remove(), but
instead of using an element as
target, it takes in an bool function.
This allows for much more complex
search algorithms
———————————————————
——————
▶︎adding a degree of abstraction is
usefull when iteracting with an
evolving third party library. In the
case of modifications to that library
in the future, changes only have to
be made to the classes directly
interacting with it
▶︎Programming by difference :
theorical concept which is to avoid
repeating code by simply adjusting
similar code to new differences. So
instead of repeating some
functions code and adding to it, you
can instead call that function
▶︎In a GUI, the first element called
is going to end up under the next
ones. Invertly, this ensures that any
new element is always going to be
appearing on top.
▶︎In a GUI, a point is simply a
location inside of a window. In
order to display a single location, it
is necessary to create an additional
structure. ( chars can be a
convenient and easy way to
represent single points)
▶︎While loop &&(and) operator will
get called in order and stop at the
first condition not met. (in the case
of a istream, if a condition breaks
before it, it won’t grab anything
from the stream)
▶︎Constants created from macros
will always refer to the information
available from the start of
compilation, so for long use of a
program, those constants can
become further away from the truth
▶︎In order to declare a variable
inside a case from a switch
statement, it’s necessary to
defined a new scope to that case.
otherwise, the switch statement
only as 1 scope for all the cases
where it could then skip the
declaration

Chapitre 14————— Graphics Class


Design

Function pointer : pointer to the CPU


instructions of a function. when referencing
a function, it doesn’t require a ‘&’ or
‘( )’ operator. The type of the pointer
being void(*name)(__) {with the underscore
being it’s parameters type}
Callback function : function used as a
parameter inside of another function and
which will then be executed inside
that second function
Lambdas : function without
identification that can be used with
a function pointer. the function
name is replaced by ‘[ ]’ brackets
which defines it’s capture mode.
[with a function pointer, the
function becomes variable like]
Capture : method with which lambdas
can retain information from there
scope to be used inside another
scope. the capture state can be all
by value, all by reference or with
specific state for a variable.
Functors : it’s a class object with a
operator overload for ‘( )’. This makes
the class name itself usable as a
function. a functor can then be
initialized for different values and be
initialized inside the parameters of a
function
‘\r’ : Carriage return (like a ‘\n’ but it stays on
the same line and overwrites it)
sprintf() : behaves as a printf(), but
instead of an output, it stored the
result in a c-string ( deprecated in
favor of snprintf() )
snprintf() : improves on sprintf() by
also taking in a maximum buffer
capacity (more secure)
strcmp() : compares two C-strings,
returning either > or < than 0 if a
char doesn’t match and based on
it’s difference
sleep() : adds delay to cpu execution.
by default in seconds. used with
<unistd.h> on linux systems. (can
help to limit cpu usage of a
program)
nil : similar to NULL but used by
convention in certain cases,
particularily in objective-c
————————————
▶︎lambdas can really help readabillity
when needing a small boolean callback
function (like in a std::find_if())

▶︎si mac demande permission de


sécurité pour l’accès au desktop à
chaque build, y faut SignIn avec
l’apple ID et changer le projet pour
qu’il soit en Automatic signing et en Sign
to Run locally.
▶︎pour éviter les pop ups de
sécurité, travailler dans un dossier
séparé des dossiers de base de
MacOS. Il est ensuit possible de
faire un alias pour avoir une copie
du nouveau dossier sur le desktop

You might also like