Code With Harry c++ Web Notes
Code With Harry c++ Web Notes
Introduction :—
C++ Overview
What is C++?
• C++ was developed by Bjarne Stroustrup, as an extension to the C language.
• Despite being an 80s creation, C++ has been a popular programming language
throughout these years.
• C++ is a cross-platform language that can be used to create high-performance
applications and software systems.
• C++ is very close to the hardware making it comparatively easy for programmers to
give the instructions directly to the system without any intermediary giving
programmers a high level of control over system resources and memory.
What is an IDE?
• IDE stands for Integrated Development Environment.
• It is nothing more than an enhanced version of a text editor that helps you write
more ef cient and nicer code.
• It helps to differentiate different parts of your codes with different colors and noti es
you if you are missing some semicolon or bracket at some place by highlighting that
area.
• A lot of IDEs are available, such as DEVC++ or Code Blocks, but we will prefer
using VS Code for this tutorial series.
Installing VSCode
• Visit https://code.visualstudio.com/download
• Click on the download option as per your operating system.
• After the download is completed, open the setup and run it by saving VS Code in
the default location without changing any settings.
• You will need to click the next button again and again until the installation process
begins.
What is a Compiler?
• A compiler is used to run the program of a certain language which is generally high-
level by converting the code into a language that is low-level that our computer
could understand.
• There are a lot of compilers available, but we will proceed with teaching you to use
MinGW for this course because it will ful ll all of our requirements, and also it is
recommended by Microsoft itself.
int main()
{
std::cout << "Hello World";
return 0;
}
Output:
Hello World
int main()
{
std::cout << "Hello World";
return 0;
}
Here’s what it can be broken down to.
De nition Section
Here, all the variables, or other user-de ned data types are declared. These variables are
used throughout the program and all the functions.
Function Declaration
• After the de nition of all the other entities, here we declare all the functions a
program needs. These are generally user-de ned.
• Every program contains one main parent function which tells the compiler where to
start the execution of the program.
• All the statements that are to be executed are written in the main function.
• Only the instructions enclosed in curly braces {} are considered for execution by the
compiler.
• After all instructions in the main function have been executed, control leaves the
main function and the program ends.
1. Keywords
Keywords are reserved words that can not be used elsewhere in the program for naming a
variable or a function. They have a speci c function or task and they are solely used for
that. Their functionalities are pre-de ned.
One such example of a keyword could be return which is used to build return statements
for functions. Other examples are auto, if, default, etc.
There is a list of reserved keywords which cannot be reused by the programmer or
overloaded. One can nd the list here, https://en.cppreference.com/w/cpp/keyword.
2. Identi ers
Identi ers are names given to variables or functions to differentiate them from one another.
Their de nitions are solely based on our choice but there are a few rules that we have
to follow while naming identi ers. One such rule says that the name can not contain
special symbols such as @, -, *, <, etc.
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
C++ is a case-sensitive language so an identi er containing a capital letter and another
one containing a small letter in the same place will be different. For example, the three
words: Code, code, and cOde can be used as three different identi ers.
3. Constants
Constants are very similar to a variable and they can also be of any data type. The only
difference between a constant and a variable is that a constant’s value never changes.
We will see constants in more detail in the upcoming tutorials.
4. String Literal
String literals or string constants are a sequence of characters enclosed in double
quotation marks. Escape sequences are also string literals.
C++ Comments
A comment is a human-readable text in the source code, which is ignored by the compiler.
Comments can be used to insert any informative piece which a programmer does not
wish to be executed. It could be either to explain a piece of code or to make it more
readable. In addition, it can be used to prevent the execution of alternative code when
the process of debugging is done.
Comments can be singled-lined or multi-lined.
Single Line Comments
• Single-line comments start with two forward slashes (//).
• Any information after the slashes // lying on the same line would be ignored (will not
be executed) since they become unparsable.
An example of how we use a single-line comment
#include <iostream>
int main()
{
// This is a single line comment
std::cout << "Hello World";
return 0;
}
Multi-line comments
fi
fi
fi
• A multi-line comment starts with /* and ends with */.
• Any information between /* and */ will be ignored by the compiler.
An example of how we use a multi-line comment
#include <iostream>
int main()
{
/* This is a
multi-line
comment */
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables.
Some of them are as follows:
• an integer variable de ned with the keyword int stores integers (whole numbers),
without decimals, such as 63 or -1.
• a oating point variable de ned with keyword oat stores oating point numbers,
with decimals, such as 79.97 or -13.26.
• a character variable de ned with the keyword char stores single characters, such
as 'A' or 'z'. Char values are bound to be surrounded by single quotes.
• a boolean variable de ned with the keyword bool stores a single value 0 or 1 for
false and true respectively.
Declaration
We cannot declare a variable without specifying its data type. The data type of a variable
depends on what we want to store in the variable and how much space we want it to
hold. The syntax for declaring a variable is simple:
data_type variable_name;
Copy
OR
data_type variable_name = value;
Copy
The tutorial will go over data types later on. They will be dealt with in great detail.
Naming a Variable
There is no limit to what we can call a variable. Yet there are speci c rules we must follow
while naming a variable:
• A variable name in C++ can have a length of range 1 to 255 characters
• A variable name can only contain alphabets, digits, and underscores(_).
fl
fi
fi
fi
fi
fl
fl
fi
• A variable cannot start with a digit.
• A variable cannot include any white space in its name.
• Variable names are case sensitive
• The name should not be a reserved keyword or any special character.
Variable Scope
The scope of a variable is the region in a program where the existence of that variable is
valid. Based on its scope, variables can be classi ed into two types:
Local variables:
Local variables are declared inside the braces of any function and can be assessed only
from that particular function.
Global variables:
Global variables are declared outside of any function and can be accessed from
anywhere.
void func()
{
cout << a << endl;
}
int main()
{
int a = 10; //local variable
cout << a << endl;
func();
return 0;
}
Copy
Output:
10
5
Copy
Explanation: A local variable a was declared in the main function, and when printed, gave
10. This is because, within the body of a function, a local variable takes precedence
over a global variable with the same name. But since there was no variable declared in
the func function, it considered the global variable a for printing, and hence the value 5.
fi
A variable, as its name is de ned, can be altered, or its value can be changed, but the
same is not true for its type. If a variable is of integer type, it will only store an integer
value through a program. We cannot assign a character type value to an integer
variable. We can not even store a decimal value into an integer variable.
Some of the popular built-in data types and their applications are:
Data Type Size Description
int 2 or 4 bytes Stores whole numbers, without decimals
Stores fractional numbers, containing one or more
oat 4 bytes
decimals. They require 4 bytes of memory
space.
Stores fractional numbers, containing one or more
double 8 bytes
decimals. They require 4 bytes of memory
char 1 byte space.
Stores a single character/letter/number, or ASCII
values
boolean 1 byte Stores true or false values
fl
fi
fi
fi
fi
fi
C++ Constants
Constants are unchangeable; when a constant variable is initialized in a program, its value
cannot be changed afterwards.
#include <iostream>
using namespace std;
int main()
{
const float PI = 3.14;
cout << "The value of PI is " << PI << endl;
PI = 3.00; //error, since changing a const variable is not
allowed.
}
Copy
Output:
error: assignment of read-only variable 'PI'
C++ Operators
Special symbols that are used to perform actions or operations are known as operators.
They could be both unary or binary.
For example, the symbol + is used to perform addition in C++ when put in between two
numbers, so it is a binary operator. There are different types of operators. They are as
follows:
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations such as addition,
subtraction, etc. They could be both binary and unary. A few of the simple arithmetic
operators are
Operation Description
a+b Adds a and b
a-b Subtracts b from a
a*b Multiplies a and b
a/b Divides a by b
a%b Modulus of a and b
a++ Post increments a by 1
a-- Post decrements a by 1
++a Pre increments a by 1
--a Pre decrements a by 1
int main()
{
int a = 4, b = 5;
cout << "The value of a + b is " << a + b << endl;
cout << "The value of a - b is " << a - b << endl;
cout << "The value of a * b is " << a * b << endl;
cout << "The value of a / b is " << a / b << endl;
cout << "The value of a % b is " << a % b << endl;
cout << "The value of a++ is " << a++ << endl;
cout << "The value of a-- is " << a-- << endl;
cout << "The value of ++a is " << ++a << endl;
cout << "The value of --a is " << --a << endl;
}
Copy
Output:
The value of a + b is 9
The value of a - b is -1
The value of a * b is 20
The value of a / b is 0
The value of a % b is 4
The value of a++ is 4
The value of a-- is 5
The value of ++a is 5
The value of --a is 4
Copy
Relational Operators
Relational operators are used to check the relationship between two operands and to
compare two or more numbers or even expressions in cases. The return type of a
relational operator is a Boolean that is, either True or False (1 or 0).
Operator Description
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Is equal to
!= Is not equal to
int main()
{
int a = 4, b = 5;
cout << "The value of a == b is " << (a == b) << endl;
cout << "The value of a < b is " << (a < b) << endl;
cout << "The value of a > b is " << (a > b) << endl;
}
Copy
Output:
The value of a==b is 0
The value of a<b is 1
The value of a>b is 0
Copy
The output is 0 for a==b, since a and b are not equal and 1 for a<b, since a is less than b.
Logical Operators
Logical Operators are used to check whether an expression is true or false. There are
three logical operators i.e. AND, OR, and NOT. They can be used to compare Boolean
values but are mostly used to compare expressions to see whether they are satisfying
or not.
• AND: it returns true when both operands are true or 1.
• OR: it returns true when either operand is true or 1.
• NOT: it is used to reverse the logical state of the operand and is true when the
operand is false.
Operator Description
&& AND Operator
|| OR Operator
! NOT Operator
int main()
{
int a = 1, b = 0;
cout << "The value of a && b is " << (a && b) << endl;
cout << "The value of a || b is " << (a || b) << endl;
cout << "The value of !a is " << (!a) << endl;
}
Copy
Output:
The value of a && b is 0
The value of a || b is 1
The value of !a is 0
Copy
Bitwise Operators
A bitwise operator is used to perform operations at the bit level. To obtain the results, they
convert our input values into binary format and then process them using whatever
operator they are being used with.
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement
>> Shift Right Operator
<< Shift Left Operator
int main()
{
int a = 13; //1101
int b = 5; //101
cout << "The value of a & b is " << (a & b) << endl;
cout << "The value of a | b is " << (a | b) << endl;
cout << "The value of a ^ b is " << (a ^ b) << endl;
cout << "The value of ~a is " << (~a) << endl;
cout << "The value of a >> 2 is " << (a >> 2) << endl;
cout << "The value of a << 2 is " << (a << 2) << endl;
}
Copy
Output:
The value of a & b is 5
The value of a | b is 13
The value of a ^ b is 8
The value of ~a is -14
The value of a >> 2 is 3
The value of a << 2 is 52
Copy
Assignment Operators
Assignment operators are used to assign values. We will use them in almost every
program we develop.
int a = 0;
int b = 1;
Copy
Equal to (=) is the assignment operator here. It is assigning 0 to a and 1 to b in the above
example.
Operator Description
= It assigns the right side operand value to the left side operand.
It adds the right operand to the left operand and assigns the result to
+=
the left operand.
It subtracts the right operand from the left operand and assigns the
-=
result to the left operand.
It multiplies the right operand with the left operand and assigns the
*=
result to the left operand.
It divides the left operand with the right operand and assigns the result
/=
to the left operand.
Operator precedence
It helps us determine the precedence of an operator over another while solving an
expression. Consider an expression a+b*c. Now, since the multiplication operator's
precedence is higher than the precedence of the addition operator, multiplication
between a and b is done rst and then the addition operation will be performed.
Operator associativity
It helps us to solve an expression; when two or more operators having the same
precedence come together in an expression. It helps us decide whether we should start
solving the expression containing operators of the same precedence from left to right or
from right to left.
The table containing the operator precedence and operator associativity of all operators
can be found here. C++ Operator Precedence - cppreference.com.
C++ Manipulators
In C++ programming, language manipulators are used in the formatting of output. These
are helpful in modifying the input and the output stream. They make use of the insertion
and extraction operators to modify the output.
Here’s a list of a few manipulators:
Manipulators Description
fi
endl It is used to enter a new line with a ush.
setw(a) It is used to specify the width of the output.
setprecision(a) It is used to set the precision of oating-point values.
setbase(a) It is used to set the base value of a numerical number.
Let’s see their implementation in C++. Note that we use the header le iomanip for some
of the manipulators.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float PI = 3.14;
int num = 100;
cout << "Entering a new line." << endl;
cout << setw(10) << "Output" << endl;
cout << setprecision(10) << PI << endl;
cout << setbase(16) << num << endl; //sets base to 16
}
Copy
Output:
Entering a new line.
Output
3.140000105
64
Input stream
In the input stream, the direction of the ow of bytes occurs from the input device (for ex
keyboard) to the main memory.
Output stream
In the output stream, the direction of ow of bytes occurs from the main memory to the
output device (for ex-display)
An example that demonstrates how input and output are popularly done in C++.
#include <iostream>
using namespace std;
fl
fl
fl
fl
fi
int main()
{
int num;
cout << "Enter a number: ";
cin >> num; // Getting input from the
user
cout << "Your number is: " << num; // Displaying the input
value
return 0;
}
Copy
Input:
Enter a number: 10
Copy
Output:
Your number is: 10
Copy
Important Points
• The sign << is called the insertion operator.
• The sign >> is called the extraction operator.
• cout keyword is used to print.
• cin keyword is used to take input at run time.
Control Structure
The work of control structures is to give ow and logic to a program. There are three types
of basic control structures in C++.
Sequence Structure
Sequence structure refers to the sequence in which program execute instructions one
after another.
Selection Structure
Selection structure refers to the execution of instruction according to the selected
condition, which can be either true or false. There are two ways to implement selection
structures. They are done either by if-else statements or by switch case statements.
Structure
fl
LOOP STRUTURE
Loop structure refers to the execution of an instruction in a loop until the condition gets
false.
C++ If Else
If else statements are used to implement a selection structure. Like any other
programming language, C++ also uses the if keyword to implement the decision control
instruction.
The condition for the if statement is always enclosed within a pair of parentheses. If the
condition is true, then the set of statements following the if statement will execute. And
if the condition evaluates to false, then the statement will not execute, instead, the
program skips that enclosed part of the code.
int main()
{
int age;
cout << "Enter a number: ";
cin >> age;
if (age >= 50)
{
cout << "Input number is greater than 50!" << endl;
}
else if (age == 50)
{
cout << "Input number is equal to 50!" << endl;
}
else
{
fi
cout << "Input number is less than 50!" << endl;
}
}
Copy
Input
Enter a number: 51
Copy
Output
Input number is greater than 50!
Copy
Note: The else if statement checks for a different condition if the conditions checked
above it evaluate to false.
case {value 2} :
do this ;
default :
do this ;
}
Copy
The break keyword in a case block indicates the end of a particular case. If we do not put
the break in each case, then even though the speci c case is executed, the switch will
continue to execute all the cases until the end is reached. The default case is optional.
Whenever the expression's value is not matched with any of the cases inside the
switch, then the default case will be executed.
case 2:
cout << "Statement 2" << endl;
break;
default:
cout << "Default statement!" << endl;
}
}
Copy
Output
Statement 2
Copy
• For Loop
• While Loop
• Do While Loop
For Loop
fi
fi
fi
A for loop is a repetition control structure that allows us to ef ciently write a loop that will
execute a speci c number of times. The for-loop statement is very specialized. We use
a for loop when we already know the number of iterations of that particular piece of
code we wish to execute. Although, when we do not know about the number of
iterations, we use a while loop which is discussed next.
int main()
{
int num = 10;
int i;
for (i = 0; i < num; i++)
{
cout << i << " ";
}
return 0;
}
Copy
Output:
0 1 2 3 4 5 6 7 8 9
Copy
First, the initialization expression will initialize loop variables. The expression i=0 executes
once when the loop starts. Then the condition i < num is checked. If the condition is
true, then the statements inside the body of the loop are executed. After the statements
inside the body are executed, the control of the program is transferred to the increment
of the variable i by 1. The expression i++ modi es the loop variables. Iteratively, the
condition i < num is evaluated again.
The for loop terminates when i nally becomes greater than num, therefore, making the
condition i<num false.
fi
fi
fi
fi
While Loop
A While loop is also called a pre-tested loop. A while loop allows a piece of code in a
program to be executed multiple times, depending upon a given test condition which
evaluates to either true or false. The while loop is mostly used in cases where the
number of iterations is not known. If the number of iterations is known, then we could
also use a for loop as mentioned previously.
int main()
{
int i = 5;
while (i < 10)
{
cout << i << " ";
i++;
}
return 0;
}
Copy
Output
5 6 7 8 9
Do While Loop
A do-while loop is a little different from a normal while loop. A do-while loop, unlike what
happens in a while loop, executes the statements inside the body of the loop before
checking the test condition.
So even if a condition is false in the rst place, the do-while loop would have already run
once. A do-while loop is very much similar to a while loop, except for the fact that it is
guaranteed to execute the body at least once.
fi
Unlike for and while loops, which test the loop condition rst, then execute the code written
inside the body of the loop, the do-while loop checks its condition at the end of the
loop.
First, the body of the do-while loop is executed once. Only then, the test condition is
evaluated. If the test condition returns true, the set of instructions inside the body of the
loop is executed again, and the test condition is evaluated. The same process goes on
until the test condition becomes false. If the test condition returns false, then the loop
terminates.
int main()
{
int i = 5;
do
{
cout << i << " ";
i++;
} while (i < 5);
return 0;
}
Output
5
Here, even if i was less than 5 from the very beginning, the do-while let the print statement
execute once, and then terminated.
•C++ Break/Continue
Break Statement
Break statement is used to break the loop or switch case statements execution and brings
the control to the next block of code after that particular loop or switch case it was used
in.
fi
Break statements are used to bring the program control out of the loop it was encountered
in. The break statement is used inside loops or switch statements in C++ language.
int main()
{
int num = 10;
int i;
for (i = 0; i < num; i++)
{
if (i == 6)
{
break;
}
cout << i << " ";
}
return 0;
}
Copy
Output
0 1 2 3 4 5
Copy
Here, when i became 6, the break statement got executed and the program came out of
the for loop.
Continue Statement
The continue statement is used inside loops in C++ language. When a continue statement
is encountered inside the loop, the control jumps to the beginning of the loop for the
next iteration, skipping the execution of statements inside the body of the loop after the
continue statement.
It is used to bring the control to the next iteration of the loop. Typically, the continue
statement skips some code inside the loop and lets the program move on with the next
iteration. It is mainly used for a condition so that we can skip some lines of code for a
particular condition.
It forces the next iteration to follow in the loop unlike a break statement, which terminates
the loop itself the moment it is encountered.
int main()
{
for (int i = 0; i <= 10; i++)
{
if (i < 6)
{
continue;
}
cout << i << " ";
}
return 0;
}
Output
6 7 8 9 10
Here, the continue statement was continuously executing while i remained less than 5. For
all the other values of i, we got the print statement working.
•C++ Arrays
•
Array Basics
An array is a collection of items that are of the data type stored in contiguous memory
locations. And it is also known as a subscript variable.
It can even store the collection of derived data types such as pointers, structures, etc.
An array can be of any dimension. The C++ Language places no limits on the number of
dimensions in an array. This means we can create arrays of any number of dimensions.
It could be a 2D array or a 3D array or more.
Advantages of Arrays?
• It is used to represent multiple data items of the same type by using only a single
name.
• Accessing any random item at any random position in a given array is very fast in
an array.
• There is no case of memory shortage or over ow in the case of arrays since the
size is xed and elements are stored in contiguous memory locations.
Array Operations
De ning an array
fi
fi
fl
1.Without specifying the size of the array:
int arr[] = {1, 2, 3};
Copy
Here, we can leave the square brackets empty, although the array cannot be left
empty in this case. It must have elements in it.
int main()
{
int arr[] = {1, 2, 3};
cout << arr[1] << endl;
}
Copy
Output:
2
Copy
int main()
{
int arr[] = {1, 2, 3};
arr[2] = 8; //changing the element on index 2
cout << arr[2] << endl;
}
Copy
Output:
8
•C++Pointers
Pointers
A pointer is a data type that holds the address of another data type. A pointer itself is a
variable that points to any other variable. It can be of type int, char, array, function, or
even any other pointer. Pointers in C++ are de ned using the ‘*’ (asterisk) operator.
The ‘&’(ampersand) operator is called the ‘address of’ operator, and the ‘*’(asterisk)
operator is called the ‘value at’ dereference operator.
Applications of a Pointer
• Pointers are used to dynamically allocate or deallocate memory.
• Pointers are used to point to several containers such as arrays, or structs, and also
for passing addresses of containers to functions.
• Return multiple values from a function
• Rather than passing a copy of a container to a function, we can simply pass its
pointer. This helps reduce the memory usage of the program.
• Pointer reduces the code and improves the performance.
Operations on Pointers
Address of Operator (&):
& is also known as the Referencing Operator. It is a unary operator. The variable name
used along with the Address of operator must be the name of an already de ned
variable.
Using & operator along with a variable gives the address number of the variable.
Here’s one example to demonstrate the use of the address of the operator.
#include <iostream>
using namespace std;
int main()
{
int a = 10;
cout << "Address of variable a is " << &a << endl;
return 0;
fi
fi
}
Copy
Output:
0x61febc
Copy
Indirection Operator
* is also known as the Dereferencing Operator. It is a unary operator. It takes an address
as its argument and returns the content/container whose address is its argument.
int main()
{
int a = 100;
cout << "Value of variable a stored at address " << &a << " is
" << (*(&a)) << endl;
return 0;
}
Copy
Output:
Value of variable a stored at address 0x61febc is 100
Copy
Pointer to Pointer
Pointer to Pointer is a simple concept, in which we store the address of one pointer to
another pointer. This is also known as multiple indirections owing to the operator’s
name. Here, the rst pointer contains the address of the second pointer, which points
to the address where the actual variable has its value stored.
int main()
{
int a = 100;
int *b = &a;
int **c = &b;
cout << "Value of variable a is " << a << endl;
cout << "Address of variable a is " << b << endl;
cout << "Address of pointer b is " << c << endl;
fi
fi
return 0;
}
Copy
Output:
Value of variable a is 100
Address of variable a is 0x61feb8
Address of pointer b is 0x61feb4
Copy
An example program for storing the starting address of an array in the pointer,
int marks[] = {99, 100, 38};
int *p = marks;
cout << "The value of marks[0] is " << *p << endl;
Output:The value of marks
value of marks[
*(p+1) returns the value at the second position in the array marks. Here’s how it works.
int marks[] = {99, 100, 38};
int *p = marks;
cout << "The value of marks[0] is " << *p << endl;
cout << "The value of marks[1] is " << *(p + 1) << endl;
cout << "The value of marks[2] is " << *(p + 2) << endl;
Copy
Output:
The value of marks[0] is 99
The value of marks[1] is 100
The value of marks[2] is 38
•C++ Strings
fi
Strings
A string is an array of characters. Unlike in C, we can de ne a string variable and not
necessarily a character array to store a sequence of characters. Data of the same type
are stored in an array, for example, integers can be stored in an integer array, similarly,
a group of characters can be stored in a character array or a string variable. A string is
a one-dimensional array of characters.
Declaring a string is very simple, the same as declaring a one-dimensional array. It’s just
that we are considering it as an array of characters.
int main()
{
// declare and initialise string
string str = "CodeWithHarry";
cout << str << endl;
return 0;
}
Output:
CodeWithHarry
Note: To be able to use these strings, you must declare another header le named
string. It contains a lot of useful string functions and libraries as well.
Structures
fi
fi
fi
Variables store only one piece of information and arrays of certain data types store the
information of the same data type. Variables and arrays can handle a great variety of
situations. But quite often, we have to deal with the collection of dissimilar data types.
For dealing with cases where there is a requirement to store dissimilar data types, C++
provides a data type called ‘structure’. The structure is a user-de ned data type that is
available in C++. Structures are used to combine different types of data types, just like
an array is used to combine the same type of data types.
Another way to store data of dissimilar data types would have been constructing individual
arrays, but that must be unorganized. It is to keep in mind that structure elements too
are always stored in contiguous memory locations.
Features of Structs
1. We can assign the values of a structure variable to another structure variable of the
same type using the assignment operator.
2. Structure can be nested within another structure which means structures can have
their members as structures themselves.
3. We can pass the structure variable to a function. We can pass the individual
structure elements or the entire structure variable into the function as an argument.
And functions can also return a structure variable.
4. We can have a pointer pointing to a struct just like the way we can have a pointer
pointing to an int, or a pointer pointing to a char variable.
Here’s one example of how a struct is de ned and used in main as a user-de ned data
type.
#include <iostream>
using namespace std;
struct employee
{
/* data */
int eId;
char favChar;
int salary;
};
int main()
fi
fi
fi
fi
{
struct employee Harry;
return 0;
}
Copy
struct employee
{
/* data */
int eId;
char favChar;
int salary;
};
int main()
{
struct employee Harry;
Harry.eId = 1;
Harry.favChar = 'c';
Harry.salary = 120000000;
cout << "eID of Harry is " << Harry.eId << endl;
cout << "favChar of Harry is " << Harry.favChar << endl;
cout << "salary of Harry is " << Harry.salary << endl;
return 0;
}
Copy
Output:
eID of Harry is 1
favChar of Harry is c
salary of Harry is 120000000
fi
Unions
Just like Structures, the union is a user-de ned data type. They provide better memory
management than structures. All the members in the unions share the same memory
location.
The union is a data type that allows different data belonging to different data types to be
stored in the same memory locations. One of the advantages of using a union over
structures is that it provides an ef cient way of reusing the memory location, as only
one of its members can be accessed at a time. A union is used in the same way we
declare and use a structure. The difference lies just in the way memory is allocated to
their members.
Here’s one example of how a union is de ned and used in main as a user-de ned data
type.
#include <iostream>
using namespace std;
union money
{
/* data */
int rice;
char car;
float pounds;
};
int main()
{
union money m1;
}
Copy
union money
{
/* data */
int rice;
char car;
float pounds;
};
int main()
{
union money m1;
m1.rice = 34;
cout << m1.rice;
return 0;
}
Copy
Output:
34
Copy
Note: We can only use 1 variable at a time otherwise the compiler will give us a garbage
value and the compiler chooses the data type which has maximum memory for the
Enums
Enum or enumeration is a user-de ned data type. Enums have named constants that
represent integral values. Enums are used to make the program more readable and
less complex. It lets us de ne a xed set of possible values and later de ne variables
having one of those values.
Enums
Creating an Enum element
We use the enum keyword to de ne the enum.
The syntax for de ning a union is,
enum enum_name
{
element1,
element2,
element3
};
Copy
fi
fi
fi
fi
fi
fi
Here’s one example of how a union is de ned and used in main as a user-de ned data
type.
enum Meal
{
breakfast,
lunch,
dinner
};
Copy
enum Meal
{
breakfast,
lunch,
dinner
};
int main()
{
Meal m1 = dinner;
if (m1 == 2)
{
cout << "The value of dinner is " << dinner << endl;
}
}
Copy
Output:
The value of dinner is 2
.
C++ FUNCTION
C++ Functions
Functions
Functions are the main part of top-down structured programming. We break the code into
small pieces and make functions of that code. Functions could be called multiple or
several times to provide reusability and modularity to the C++ program.
fi
fi
Functions are also called procedures or subroutines or methods and they are often
de ned to perform a speci c task. And that makes functions a group of code put
together and given a name that can be called anytime without writing the whole code
again and again in a program.
Advantages of Functions
• The use of functions allows us to avoid re-writing the same logic or code over and
over again.
• With the help of functions, we can divide the work among the programmers.
• We can easily debug or can nd bugs in any program using functions.
• They make code readable and less complex.
Aspects of a function
• Declaration: This is where a function is declared to tell the compiler about its
existence.
• De nition: A function is de ned to get some task executed. (It means when we
de ne a function, we write the whole code of that function and this is where the
actual implementation of the function is done).
• Call: This is where a function is called in order to be used.
Types of functions
Library functions:
Library functions are pre-de ned functions in C++ Language. These are the functions that
are included in C++ header les prior to any other part of the code in order to be used.
E.g. sqrt(), abs(), etc.
Formal Parameters
So, the variable which is declared in the function is called a formal parameter or simply, a
parameter. For example, variables a and b are formal parameters.
int sum(int a, int b){
//function body
}
Copy
Actual Parameters
The values which are passed to the function are called actual parameters or simply,
arguments. For example, the values num1 and num2 are arguments.
int sum(int a, int b);
int main()
{
int num1 = 5;
int num2 = 6;
sum(num1, num2);//actual parameters
}
Copy
A function doesn't need to have parameters or it should necessarily return some value.
Methods
Now, there are methods using which arguments are sent to the function. They are,
int main()
{
int x = 5, y = 6;
cout << "The value of x is " << x << " and the value of y is "
<< y << endl;
swap(x, y);
cout << "The value of x is " << x << " and the value of y is "
<< y << endl;
}
Copy
Output:
The value of x is 5 and the value of y is 6
The value of x is 5 and the value of y is 6
Copy
int main()
{
int x = 5, y = 6;
cout << "The value of x is " << x << " and the value of y is "
<< y << endl;
swap(&x, &y);
cout << "The value of x is " << x << " and the value of y is "
<< y << endl;
}
Copy
Output:
The value of x is 5 and the value of y is 6
The value of x is 6 and the value of y is 5
Copy
int main()
{
int x = 5, y = 6;
cout << "The value of x is " << x << " and the value of y is "
<< y << endl;
swap(x, y);
cout << "The value of x is " << x << " and the value of y is "
<< y << endl;
}
Copy
Output
The value of x is 5 and the value of y is 6
The value of x is 6 and the value of y is 5
Copy
Two special methods that are often used by programmers to have their program work
ef ciently are,
fi
Default Arguments in C++
Default arguments are those values which are used by the function if we don’t input our
value as parameter. It is recommended to write default arguments after the other
arguments.
Recursion
When a function calls itself, it is called recursion and the function which is calling itself is
called a recursive function. The recursive function consists of a base condition and a
recursive condition.
Recursive functions must be designed with a base case to make sure the recursion stops,
otherwise, they are bound to execute forever and that's not what you want. The case in
which the function doesn’t recur is called the base case. For example, when we try to
nd the factorial of a number using recursion, the case when our number becomes
smaller than 1 is the base case.
An example of a recursive function is the function for calculating the factorial of a number.
int factorial(int n){
if (n == 0 || n == 1){
return 1;
}
return n * factorial(n - 1);
}
Function Overloading
Function overloading is a process to make more than one function with the same name
but different parameters, numbers, or sequences. Now, there are a few conditions and
any number of functions with the same name following any of these are called
overloaded.
Same name but different data type of parameters
Example
float sum(int a, int b);
float sum(float a, float b);
fi
fi
fi
Copy
•C++ OOPS
•
C++ language was designed with the main intention of adding object-oriented
programming to C language. As the size of the program increases, the readability,
maintainability, and bug-free nature of the program decrease. The main aim of OOP is
to bind together the data and the functions that operate on them so that no other part of
the code can access this data except that function.
This was the major problem with languages like C which relied upon functions or
procedures (hence the name procedural programming language). As a result, the
possibility of not addressing the problem adequately was high. Also, data was almost
neglected, and data security was easily compromised Using classes solves this
problem by modeling the program as a real-world scenario.
Difference between Procedure Oriented Programming
and Object-Oriented Programming
Procedure Oriented Programming
• Consists of writing a set of instructions for the computer to follow
• The main focus is on functions and not on the ow of data
• Functions can either use local or global data
• Data moves openly from function to function
Object - Oriented Programming
• Works on the concept of classes and object
• A class is a template to create objects
• Treats data as a critical element
• Decomposes the problem in objects and builds data and functions around the
objects
Basically, procedural programming involves writing procedures or functions that
manipulate data, while object-oriented programming involves creating objects that
contain both data and functions.
Objects
Objects are instances of a class. To create an object, we just have to specify the class
name and then the object’s name. Objects can access class attributes and methods
which are bound to the class de nition. It is recommended to put these attributes and
methods in access modi ers so that their permissions can be better speci ed to allow
them to be used by objects.
int main()
{
class_name object_name; //object
}
int main()
{
Employee Harry;
}
Copy
A class named Employee is built and two members, eId and eName are de ned inside the
class. These two members are variables and are known as class attributes. Now, an
object named Harry is de ned in the main. Harry can access these attributes using the
dot operator. But they are not accessible to Harry unless they are made public.
class Employee
{
public:
int eID;
string eName;
};
int main()
{
Employee Harry;
Harry.eID = 5;
Harry.eName = "Harry";
cout << "Employee having ID " << Harry.eID << " is " <<
Harry.eName << endl;
}
Copy
Output
Employee having ID 5 is Harry
Copy
Class methods are nothing but functions that are de ned in a class or belong to a class.
Methods belonging to a class are accessed by their objects in the same way that they
access attributes. Functions can be de ned in two ways so that they belong to a class.
• De ning inside the class
An example that demonstrates de ning functions inside classes is
class Employee
{
fi
fi
fi
fi
fi
fi
public:
int eID;
string eName;
void printName()
{
cout << eName << endl;
}
};
Copy
•
• De ning outside the class
Although, a function can be de ned outside the class, it needs to be declared inside. Later,
we can use the scope resolution operator (::) to de ne the function outside.
An example that demonstrates de ning functions outside classes is
class Employee
{
public:
int eID;
string eName;
void printName();
};
void Employee::printName()
{
cout << eName << endl;
}
The memory is not allocated to the variables when the class is declared. At the same time,
single variables can have different values for different objects, so every object has an
fi
fi
fi
fi
individual copy of all the variables of the class. But the memory is allocated to the
function only once when the class is declared. So the objects don’t have individual
copies of functions only one copy is shared among each object.
public:
static int count; //returns number of employees
string eName;
class Employee
{
public:
static int count; //static variable
string eName;
int main()
{
Employee Harry;
Harry.setName("Harry");
cout << Employee::getCount() << endl;
}
Copy
Output:
1
return_type class_name::function_name(arguments)
{
//body of the function
}
Copy
C++ Constructors
A constructor is a special member function with the same name as the class. The
constructor doesn’t have a return type. Constructors are used to initialize the objects of
their class. Constructors are automatically invoked whenever an object is created.
class Employee
{
public:
static int count; //returns number of employees
string eName;
//Constructor
Employee()
{
count++; //increases employee count every time an object
is defined
}
int main()
{
Employee Harry1;
Employee Harry2;
Employee Harry3;
cout << Employee::getCount() << endl;
}
Output:
3
public:
Employee(int a, int b = 9);
};
Copy
public:
//copy constructor
class_name(class_name &obj)
{
a = obj.a;
}
};
C++ Encapsulation
Encapsulation is the rst pillar of Object Oriented Programming. It means wrapping up
data attributes and methods together. The goal is to keep sensitive data hidden from
users.
Encapsulation is considered a good practice where one should always make attributes
private for them to become non-modi able until needed. The data is ultimately more
secure as a result of this. Once members are made private, methods to access them or
change them should be declared.
class class_name
{
private:
int a;
public:
void setA(int num)
{
a = num;
}
int getA()
{
return a;
}
};
int main()
{
class_name obj;
obj.setA(5);
cout << obj.getA() << endl;
}
Output:
5
C++ Inheritance
What is Inheritance in C++?
fi
fi
The concept of reusability in C++ is supported using inheritance. We can reuse the
properties of an existing class by inheriting it and deriving its properties. The existing
class is called the base class and the new class which is inherited from the base class
is called the derived class.
For example, we have two classes ClassA and ClassB. If ClassB is inherited from ClassA,
it means that ClassB can now implement the functionalities of ClassA. This is single
inheritance.
class ClassA
{
//body of ClassA
};
• Multiple Inheritance
Multiple inheritances is a type of inheritance in which one derived class is inherited from
more than one base class.
For example, we have three classes ClassA, ClassB, and ClassC. If ClassC is
inherited from both ClassA & ClassB, it means that ClassC can now implement the
functionalities of both ClassA & ClassB. This is multiple inheritances.
class ClassA
{
//body of ClassA
};
class ClassB
{
//body of ClassB
};
• Hierarchical Inheritance
A hierarchical inheritance is a type of inheritance in which several derived classes are
inherited from a single base class.
For example, we have three classes ClassA, ClassB, and ClassC. If ClassB and Class C
are inherited from ClassA, it means that ClassB and ClassC can now implement the
functionalities of ClassA. This is hierarchical inheritance.
class ClassA
{
//body of ClassA
};
• Multilevel Inheritance
Multilevel inheritance is a type of inheritance in which one derived class is inherited from
another derived class.
For example, we have three classes ClassA, ClassB, and ClassC. If ClassB is inherited
from ClassA and ClassC is inherited from ClassB, it means that ClassB can now
implement the functionalities of ClassA and ClassC can now implement the
functionalities of ClassB. This is multilevel inheritance.
class ClassA
{
//body of ClassA
};
• Hybrid Inheritance
Hybrid inheritance is a combination of different types of inheritances.
For example, we have four classes ClassA, ClassB, ClassC, and ClassD. If ClassC is
inherited from both ClassA and ClassB and ClassD is inherited from ClassC, it means
that ClassC can now implement the functionalities of both ClassA and ClassB and
ClassD can now implement the functionalities of ClassC. This is multilevel inheritance
where both multilevel and multiple inheritances are present.
class ClassA
{
//body of ClassA
};
class ClassB
{
//body of ClassB
};
A table is shown below which shows the behavior of access modi ers when they
are derived from public, private, and protected.
C++ Polymorphism
Polymorphism in C++
Poly means several and morphism means form. Polymorphism is something that has
several forms or we can say it as one name and multiple forms. There are two types of
polymorphism:
• Compile-time polymorphism
• Run time polymorphism
• Operator Overloading
This is a feature that lets us de ne operators working for some speci c tasks. Using the
operator +, we can add two strings by concatenating and add two numerical values
arithmetically at the same time. This is operator overloading.
fi
fi
Run Time Polymorphism
With run-time polymorphism, the compiler has no idea what will happen when the code is
executed. Run time polymorphism is also called late binding. The run-time
polymorphism is considered slow because function calls are decided at run time. Run
time polymorphism can be achieved from virtual functions.
The le is a patent of data stored on the disk. Anything written inside the le is
called a patent, for example: “#include” is a patent. The text le is the
combination of multiple types of characters, for example, the semicolon “;” is a
character.
The computer read these characters in the le with the help of the ASCII code. Every
character is mapped on some decimal number. For example, the ASCII code for the
character A is 65 which is a decimal number. These decimal numbers are converted
fi
fi
fi
fi
fi
fi
into binary numbers to make them readable for the computer because the computer
can only understand the language of 0 & 1.
A large program deployed for heavy applications cannot function without les, since we
can get input from them as well as print output from them very easily. We can also save
a lot of program space by accessing the le's data only when needed, making the
program more ef cient and faster.
Files are stored in non-volatile memory which is better in terms of storing data. Non-
volatile memory stays intact even after the system shuts down. They get retrieved again
after the system is turned on.
Operations on les
There are basically four operations we can perform on les in C.
• Creating a File:
We can create a le using C++ language, in any directory, without even leaving our
compiler. We can select the name or type we want our le to have, along with its
location.
• Opening a File:
We can open an existing le and create a new le and open it using our program. We can
perform different operations on a le after it has been opened.
• Closing a File:
When we are done with the le, meaning that we have performed whatever we want to
perform on our le, we can close the le using the close function.
• Read/Write to a le:
After opening a le, we can access its contents and read, write, or update them.
The fstream library allows us to handles les. So, to be able to use les in a program,
one must include the <fstream> header le.
A. Opening a le
In order to work with les in C++, we will rst have to open it. Primarily, there are two ways
to open a le:
• Using the constructor
• Using the member function open() of the class
A le could be opened for a number of uses. It could be to write to it or to read from it.
int main()
{
ofstream out("example.txt");
return 0;
}
The le example.txt gets created if it’s not already there in the system and opened. Object
out gets created of the type ofstream, which means it could only be used to write into
the opened le.
This is how we use the constructor ofstream to open a le. Another example demonstrates
the use of the ifstream constructor.
#include <iostream>
#include <fstream>
int main()
{
ifstream in("example.txt");
return 0;
}
Copy
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
For this to work, a le named example.txt must already be created and present in the
same folder as that of the program. Object in gets created of the type ifstream, which
means it could only be used to read from the le.
B. Closing a le
When working with C++, closing open les is considered a good practice. A programmer
often makes the mistake of not closing an open le. This becomes crucial because les
do not automatically get closed after a program uses them. The closing has to be done
manually.
To close a le, we have to use the close method. This is how we use them in C++.
Syntax:
file_objectname.close();
C. Writing to a le
Writing to a le is as easy as printing any other stuff in C++. It is very similar to what we
used to do when we had to print an output in the terminal. In order to write to a le, we
use the insertion operator (<<). First, we create an object of the type ofstream and pass
the name of the le along with its extension to the method. And then, use the extraction
operator to write stuff in the le fed to the object.
Example:
#include <iostream>
#include <fstream>
int main()
{
string str = "Welcome_To_CodeWithHarry!";
ofstream out("example.txt");
out << str;
return 0;
}
D. Reading a le
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
Reading from a le is as easy as reading any other stuff as an input in C++. It is very
similar to what we used to do when we had to read input from the terminal. In order to
read from a le, we use the extraction operator (>>). First, we create an object of the
type ifstream and pass the name of the le along with its extension to the method. And
then, use the extraction operator to read stuff from the le fed to the object.
Example:
#include <iostream>
#include <fstream>
int main()
{
string str;
ifstream in("example.txt");
in >> str;
cout << str;
return 0;
}
The file example.txt had “Welcome_To_CodeWithHarry!” as its
content, hence the output:
Welcome_To_CodeWithHarry!
fi
fi
fi
fi
fi
• C++ Templates & STL
C++ Templates
What are templates?
A template is believed to escalate the potential of C++ several fold by giving it the ability to
de ne data types as parameters making it useful to reduce repetitions of the same
declaration of classes for different data types.
Declaring classes for every other data type doesn't completely utilize the potential of C++.
It is very analogous to when we said classes are the templates for objects, here
templates themselves are the templates of the classes. That is, what classes are for
objects, templates are for classes.
Syntax of a template
Consider a class containing two elements, an integer pointer, and an integer variable size.
This class acts like an array of integers with a given length size. We often name them a
vector.
class vector
{
int *arr;
int size;
};
But, if we need another array of some other data type, we will have to rede ne another
class for the same. To avoid that repetition of logic, templates help. Here’s how we do
subtle changes in the same de nition of the class for an integer array to make it generic
for any other data type as well.
So, the same vector can now be used as an integer array as well as a oat or character
array.
#include <iostream>
using namespace std;
int main()
{
vector<int> v1();
fi
fi
fi
fi
fl
fi
vector<float> v2();
}
Class templates are helpful for classes that are independent of the data type. And like any
other function, there could be more than one parameter to a template. On the basis of
the number of parameters of a template, they could be single parameters as well as
multiple parameters.
A. Single parameter
Syntax for declaring a single parametrized template is,
#include <iostream>
using namespace std;
int main()
{
//body of main
}
Copy
The example of the vector easily demonstrates how templates are used with a single
parameter.
#include <iostream>
using namespace std;
int main()
{
vector<int> v1();
vector<float> v2();
}
Copy
B. Multiple Parameter
Syntax for declaring a multiple parametrized template is,
#include <iostream>
using namespace std;
int main()
{
//body of main
}
Copy
The difference lies only in the number of parameters we declare inside the template.
Consider an example that demonstrates the use of multiple parameters in a class
template.
#include <iostream>
using namespace std;
class myClass
{
public:
T1 data1;
T2 data2;
myClass(T1 a, T2 b)
{
data1 = a;
data2 = b;
}
void display()
{
cout << this->data1 << " " << this->data2;
}
};
int main()
{
myClass<char, int> obj('C', 1);
obj.display();
}
Copy
Output
C 1
Copy
Now, we de ned an object obj in myClass to hold a character and an integer data. It could
be anything else since both the parameters have been generalized using the template.
C. Default Parameter
C++ Templates have this additional ability to have default parameters. Its ability to have
default speci cations about the data type, when it receives no arguments from the main
is a powerful attribute.
myClass(T1 a, T2 b, T3 c)
{
data1 = a;
data2 = b;
data3 = c;
fi
fi
}
void display()
{
cout << "The value of a is " << data1 << endl;
cout << "The value of b is " << data2 << endl;
cout << "The value of c is " << data3 << endl;
}
};
int main()
{
myClass<> obj1(1, 4.3, 'C');
obj1.display();
}
Copy
Output
The value of a is 1
The value of b is 4.3
The value of c is C
Copy
The template has default de ned its parameters as an integer, a oat, and a character.
Now, if the programmer wishes to change the data types, it must be exclusively
mentioned and the object must be de ned as it was done in earlier examples.
int main()
{
float avg = findAverage(5.1, 2);
cout << avg << endl;
}
Copy
Output
3.55
Copy
Both class templates and function templates help reduce the size of the program and
make it more readable.
C++ STL
What is Standard Template Library?
Competitive programming is a part of various environments, be it job interviews, coding
contests, and all, and if you’re in one of those environments, you’ll be given limited time
to code your program. So, suppose you want in your program, a resizable array, sort an
array or any other data structure. or search for some element in your container. You will
always try to code a function that will execute the above-mentioned things, and end up
losing a great amount of time. But here is when you will use STL.
An STL is a library of generic functions and classes which saves you time and energy
which you would have spent constructing for your use. This helps you reuse these well-
tested classes and functions an umpteenth number of times according to your own
convenience. To put this simply, STL is used because it is not a good idea to reinvent
something which is already built and can be used to innovate things further. Suppose
fi
fl
fi
you go to a company that builds cars, they will not ask you to start from scratch, but to
start from where it is left. This is the basic idea behind using STL.
• Algorithm
Algorithms are sets of instructions that manipulate the input data to arrive at some desired
result. In STL, we have already written algorithms, for example, to sort some data
structure, or search some element in an array. These algorithms use function
templates.
• Iterators
Iterators are objects which refer to an element in a container. And we handle them very
much similar to a pointer. Their basic job is to connect algorithms to the container and
play a vital role in the manipulation of the data.
C++ Containers
As discussed earlier, containers are objects that store information and they are nothing but
class templates with speci c functionalities. Containers themselves are of three types:
Sequence Containers
A sequence container stores that data in a linear fashion. Sequence containers include
Vector, List, Dequeue, etc. These are some of the most used sequence containers.
Associative Containers
An associative container is designed in such a way that enhances the accessing of some
element in that container. It is very much used when the user wants to fastly reach
some element. Some of these containers are, Set, Multiset, Map, Multimap etc. They
store their data in a tree-like structure.
Derived Containers
As the name suggests, these containers are derived from either the sequence or the
associative containers. They often provide you with some better methods to deal with
fi
fi
your data. They deal with real life modeling. Some examples of derived containers are
Stack, Queue, Priority Queue, etc.
C++ Vectors
A. What are vectors?
Vectors are sequence containers that fall under the category of class templates. They are
used to store information in a linear fashion. Elements of a single data type can be
stored in a vector. In a vector, we can access elements faster in comparison to arrays.
Although, insertion and deletion at some random position, except at the end is
comparatively slower. And inserting any element at the end happens faster.
Vectors provide certain methods to be used to access and utilize the elements of a vector,
the rst one being, the push_back method. To access all the methods and member
functions in detail, one can visit this site, std::vector - C++ Reference.
C. Initialising a vector
A vector could be initialized in different ways:
• In the rst method, a vector could be initialized with all the elements inserted in the
vector at the time it is de ned.
vector<int> v = {1, 2, 3, 4};
• Another method to initialize a vector is where we pass two parameters along with its
de nition where the rst parameter de nes the size of the vector and the second
parameter is the uniform value it will have at all its positions.vector<int> v(4,
10);
Copy
void display(vector<int> v)
{
cout << "The elements are: ";
for (auto it : v)
{
cout << it << " ";
}
cout << endl;
}
int main()
{
vector<int> v = {1, 2, 3, 4};
display(v);
v.push_back(5); //5 is inserted at the back
display(v);
}
Copy
Output
The elements are: 1 2 3 4
The elements are: 1 2 3 4 5
Copy
Another method to insert an element allows us to insert at any random position. Here, we
use the insert() method. The syntax for using the insert method is
vector_name.insert(iterator, element);
Here, the iterator is the pointer to that position where the element gets inserted. An
example that demonstrates the use of the insert() method is
#include <iostream>
#include <vector>
using namespace std;
void display(vector<int> v)
{
cout << "The elements are: ";
for (auto it : v)
{
cout << it << " ";
}
cout << endl;
}
int main()
{
vector<int> v = {1, 2, 3, 4};
display(v);
v.insert(v.begin(), 5);
display(v);
}
Copy
Output
The elements are: 1 2 3 4
The elements are: 5 1 2 3 4
Copy
Here, we used the begin() method which returned an iterator to the rst position of the
vector. We can manipulate it accordingly to point at the desired position by general
arithmetic operations.
Another method that gets added for vectors is the at() method which accepts the index
number as its parameter and returns the element at that position.
vector<int> v = {1, 2, 3, 4};
cout << "Element at index 2 is " << v.at(2) << endl;
Copy
Output
Element at index 2 is 3
Copy
void display(vector<int> v)
{
cout << "The elements are: ";
for (auto it : v)
{
cout << it << " ";
}
cout << endl;
}
int main()
{
vector<int> v = {1, 2, 3, 4};
display(v);
v.pop_back(); //4 gets popped from the back
display(v);
}
Copy
Output
The elements are: 1 2 3 4
The elements are: 1 2 3
Copy
Another method to remove an element allows us to remove it from any random position.
Here, we use the erase() method. The syntax for using the erase method is
vector_name.erase(iterator);
Copy
Here, the iterator is the pointer to that position where the element gets popped from. An
example that demonstrates the use of the erase() method is
#include <iostream>
#include <vector>
using namespace std;
void display(vector<int> v)
{
cout << "The elements are: ";
for (auto it : v)
{
cout << it << " ";
}
cout << endl;
}
int main()
{
vector<int> v = {1, 2, 3, 4};
display(v);
v.erase(v.begin());
display(v);
}
Copy
Output
The elements are: 1 2 3 4
The elements are: 2 3 4
C++ Lists
A. What are lists?
Lists are sequence containers that fall under the category of class templates. They are
also used to store information in a linear fashion. Only elements of a single data type
can be stored in a list. In a list, we have faster insertion and deletion of elements as
compared to other containers such as arrays and vectors. Although, accessing
elements at some random position, is comparatively slower.
Lists provide certain methods to be used to access and utilize the elements of a list, the
rst one being, the push_back method. To access all the methods and member
functions in detail, one can visit this site, std::list.
D. Initialising a list
fi
fi
fi
fi
fi
A list could be initialized in a very similar way we used to initialize a vector.: A list could be
initialized with all the elements inserted in the list at the time it is de ned.
list<int> l = {1, 2, 3, 4};
Copy
void display(list<int> l)
{
cout << "The elements are: ";
for (auto it : l)
{
cout << it << " ";
}
cout << endl;
}
int main()
{
list<int> l = {1, 2, 3, 4};
display(l);
l.push_back(5);
display(l);
l.push_front(0);
display(l);
}
Copy
Output:
The elements are: 1 2 3 4
The elements are: 1 2 3 4 5
The elements are: 0 1 2 3 4 5
Copy
fi
Another method to insert an element allows us to insert at any random position. Here, we
use the insert() method. The syntax for using the insert method is
list_name.insert(iterator, element);
Copy
Here, the iterator is the pointer to that position where the element gets inserted. An
example that demonstrates the use of the insert() method is
list<int> l = {1, 2, 3, 4};
display(l);
auto it = l.begin();
it++;
it++;
l.insert(it, 5); //5 is inserted at the third position
display(l);
Copy
Output:
The elements are: 1 2 3 4
The elements are: 1 2 5 3 4
Copy
We have to use the iterators to manually traverse through the list to reach a speci c
element or position and then dereference the iterator to retrieve the value at that
position.
list<int> l = {1, 2, 3, 4};
list<int>::iterator it = l.begin();
it++;
it++;
cout << "Element at index 2 is " << *it << endl;
Copy
Output:
Element at index 2 is 3
Copy
void display(list<int> l)
{
cout << "The elements are: ";
for (auto it : l)
{
cout << it << " ";
}
cout << endl;
}
int main()
{
list<int> l = {1, 2, 3, 4};
display(l);
l.pop_back();
display(l);
l.pop_front();
display(l);
}
Copy
Output
The elements are: 1 2 3 4
The elements are: 1 2 3
The elements are: 2 3
Copy
Another method to remove an element allows us to remove it from any random position.
Here, we use the erase() method. The syntax for using the erase method is
list_name.erase(iterator);
Copy
Here, the iterator is the pointer to that position where the element gets erased from. An
example that demonstrates the use of the erase() method is
list<int> l = {1, 2, 3, 4};
display(l);
auto it = l.begin();
it++;
it++;
l.erase(it); //element at index 2 gets erased
display(l);
Output
The elements are: 1 2 3 4
The elements are: 1 2 4
C++ Maps
A. What are maps?
A map in C++ STL is an associative container that stores key-value pairs. To elaborate, a
map stores a key of some data type and its corresponding values of some data type. All
keys in a map are of a single data type and all values in a map are of a single data
type. A map always sorts these key-value pairs by the key elements in ascending order.
Maps provide certain methods to be used to access and utilize the elements of a map. A
few of them are discussed. To access all the methods and member functions in detail,
one can visit this site, std::map.
C. Initialising a map
A map could be initialized in a similar way we used to initialize a vector or a list. It is just
that it would be pairs of elements and not just single elements while we initialize a
map. A map could be initialized with all the key-value pairs inserted in the map at the
time it is de ned.
map<string, int> m = {{“Harry”, 2}, {“Rohan”, 4}};
Copy
Insertion in a map could be done using the index operators [ ]. The key is put inside the
operator and the value is assigned to it. This key-value pair then gets inserted into the
map.
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, int> m = {{"Harry", 2}, {"Rohan", 4}};
display(m);
m["Coder"] = 3;
display(m);
}
Copy
Output:
The elements are:
Harry -> 2
Rohan -> 4
Another method to insert an element is using the insert() method and this allows us to
insert as many key-value pairs as we want. The syntax for using the insert method is
map_name.insert({key-value pair});
Copy
An example that demonstrates the use of the insert() method is
map<string, int> m = {{"Harry", 2}, {"Rohan", 4}};
display(m);
m.insert({{"Coder", 3}, {"Rahul", 5}});
display(m);
Copy
Output:
The elements are:
Harry -> 2
Rohan -> 4
Removal of elements from a map could be done using the erase() method. The erase()
method takes both the keys or an iterator to delete elements. The syntax for using the
erase method is
map_name.erase(iterator);
//OR
map_name.erase(key);
Copy
Here, the iterator is the pointer to that position where the element gets erased from and
the key is the key of that key-value pair that needs to be removed.
An example that demonstrates the use of the erase() method using a key is
map<string, int> m = {{"Harry", 2}, {"Rohan", 4}};
display(m);
m.erase("Harry");
display(m);
Output:
The elements are:
Harry -> 2
Rohan -> 4
An example that demonstrates the use of the erase() method using a pointer is
map<string, int> m = {{"Harry", 2}, {"Rohan", 4}};
display(m);
m.erase(m.begin()); //deletes the first element
display(m);
Output:
The elements are:
Harry -> 2
Rohan -> 4