Created by Bjarne Stroustrup as an extension of the C language
One of the world’s most popular programming language (lots of development resources online)
Allows for object-oriented programming
C++ is strongly typed, meaning the variable type must be defined before it is used
Lines end in semi-colons
Everything must be declared first, even functions
Indexing starts at 0!!
Basic math operators the same as R (=,+,-,/,*)
Code must first be compiled before it is run
include <iostream>
: allows the program to access
the iostream libraryusing namespace std
: allows access to objects and
variables from the standard library
using namespace std
not included, the user would
need to specify std::cout
int main
:
int
declares the type of the function named
main
cout
: prints a messages directly to the screen when the
program is runIf a function is not expected to return a value, then
void
can be used. The above program can be re-written:
bool
: Boolean (lowercase: true
or
false
)char
: Characterint
: Integerfloat
: Floating pointdouble
: Double floating pointvoid
: No return valueThe following program takes two integers as inputs and return an integer output:
The above program will fail if inputs are decimals. An additional program is needed to handle the different data type. The following will return a floating point output:
std::vector
: vector from standard library
std::vector
has a number of member functions that can
be used to operate on the vector
begin
: return iterator to beginningend
: return iterator to endsize
: returns vector sizeresize
: changes the vector size[]
: access elementfront
: access first elementback
: access last elementpush_back
: append element to endpop_back
: delete last elementclear
: clear contentThe following program initializes a vector, resizes it, adds elements, and returns the vector:
#include <iostream>
std::vector<double> create_vector() {
std::vector<double> x;
x.resize(3);
x[0] = 1.3;
for(int i=1; i<3; i++){
x[i] = x[i-1] + 1.3;
}
x.push_back(8.1);
return x;
}
The above program returns the following vector of four:
1.3 2.6 3.9 8.1